@weglot/translate-react 0.1.0 → 0.2.0
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/README.md +13 -4
- package/build/plugin/build-translator.cjs +4 -1
- package/build/plugin/build-translator.mjs +4 -1
- package/build/plugin/build-translator.mjs.map +1 -1
- package/build/plugin/next.cjs +1 -0
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +1 -0
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/vite.cjs +1 -1
- package/build/plugin/vite.mjs +1 -1
- package/build/plugin/vite.mjs.map +1 -1
- package/build/plugin/webpack.cjs +1 -1
- package/build/plugin/webpack.mjs +1 -1
- package/build/plugin/webpack.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.cts +2 -2
- package/build/react/shared/WeglotProvider.d.cts +2 -2
- package/build/runtime/translate-dynamic.cjs +5 -3
- package/build/runtime/translate-dynamic.d.cts.map +1 -1
- package/build/runtime/translate-dynamic.d.mts.map +1 -1
- package/build/runtime/translate-dynamic.mjs +6 -4
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/translation-service.cjs +4 -2
- package/build/translators/translation-service.mjs +4 -2
- package/build/translators/translation-service.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +75 -23
- package/build/translators/weglot/api-client.mjs +75 -24
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/build/translators/weglot/engine.cjs +2 -5
- package/build/translators/weglot/engine.mjs +2 -5
- package/build/translators/weglot/engine.mjs.map +1 -1
- package/build/translators/weglot/translator.cjs +31 -25
- package/build/translators/weglot/translator.mjs +31 -25
- package/build/translators/weglot/translator.mjs.map +1 -1
- package/build/types.d.cts +13 -3
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +13 -3
- package/build/types.d.mts.map +1 -1
- package/build/utils/config-factory.cjs +18 -4
- package/build/utils/config-factory.mjs +19 -5
- package/build/utils/config-factory.mjs.map +1 -1
- package/build/virtual/code-generator.cjs +2 -0
- package/build/virtual/code-generator.mjs +2 -0
- package/build/virtual/code-generator.mjs.map +1 -1
- package/build/virtual/config.cjs +3 -0
- package/build/virtual/config.d.cts +3 -1
- package/build/virtual/config.d.cts.map +1 -1
- package/build/virtual/config.d.mts +3 -1
- package/build/virtual/config.d.mts.map +1 -1
- package/build/virtual/config.mjs +3 -1
- package/build/virtual/config.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -3,25 +3,17 @@ const require_definitions_generated = require('./definitions/definitions.generat
|
|
|
3
3
|
|
|
4
4
|
//#region src/translators/weglot/api-client.ts
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - Translation: POST https://api.weglot.com/translate?api_key=<key>
|
|
9
|
-
* - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,
|
|
10
|
-
* api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).
|
|
11
|
-
*
|
|
12
|
-
* Translations made through the API are recorded in the Weglot project and
|
|
13
|
-
* can be reviewed/edited in the Weglot dashboard.
|
|
6
|
+
* Weglot API client. Weglot translates with an LLM: a word not translated yet
|
|
7
|
+
* comes back null and is queued, so callers poll until it is ready.
|
|
14
8
|
*/
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const V1_KEY_PREFIX = "wg_";
|
|
9
|
+
const DEFAULT_SETTINGS_URL = "https://api.weglot.com/project-settings";
|
|
10
|
+
const DEFAULT_API_BASE_URL = "https://api.weglot.com";
|
|
11
|
+
const SUPPORTED_PRODUCT = "2.0";
|
|
19
12
|
const WORD_TYPE_TEXT = require_definitions_generated.WORD_TYPE.TEXT;
|
|
20
13
|
const REQUEST_URL = "https://compiler.weglot.com/";
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
14
|
+
const WORD_LABEL = "translate-react";
|
|
15
|
+
const MAX_WORDS_PER_REQUEST = 100;
|
|
16
|
+
const DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
25
17
|
/** The API validates the pair independently of the project's languages, so
|
|
26
18
|
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
27
19
|
var UnsupportedLanguagePairError = class extends Error {
|
|
@@ -32,21 +24,34 @@ var UnsupportedLanguagePairError = class extends Error {
|
|
|
32
24
|
this.name = "UnsupportedLanguagePairError";
|
|
33
25
|
}
|
|
34
26
|
};
|
|
27
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
35
28
|
var WeglotApiClient = class {
|
|
36
|
-
|
|
29
|
+
apiBaseUrl;
|
|
30
|
+
constructor(apiKey, apiBaseUrl) {
|
|
37
31
|
this.apiKey = apiKey;
|
|
32
|
+
this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
|
|
38
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* One request. A word the API has queued comes back null; a word it will
|
|
36
|
+
* never translate comes back as its source text.
|
|
37
|
+
*/
|
|
39
38
|
async translate(params) {
|
|
40
|
-
const
|
|
39
|
+
const query = params.live ? "?live=1" : "";
|
|
40
|
+
const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
|
|
41
41
|
method: "POST",
|
|
42
|
-
headers: {
|
|
42
|
+
headers: {
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
Accept: "application/json",
|
|
45
|
+
Authorization: `Key ${this.apiKey}`
|
|
46
|
+
},
|
|
43
47
|
body: JSON.stringify({
|
|
44
48
|
l_from: params.from,
|
|
45
49
|
l_to: params.to,
|
|
46
50
|
request_url: REQUEST_URL,
|
|
47
51
|
words: params.words.map((w, index) => ({
|
|
48
52
|
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
49
|
-
w
|
|
53
|
+
w,
|
|
54
|
+
l: [WORD_LABEL]
|
|
50
55
|
}))
|
|
51
56
|
})
|
|
52
57
|
});
|
|
@@ -55,19 +60,65 @@ var WeglotApiClient = class {
|
|
|
55
60
|
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
56
61
|
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
57
62
|
}
|
|
58
|
-
const
|
|
63
|
+
const data = await response.json();
|
|
64
|
+
const toWords = data.to_words;
|
|
59
65
|
if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
|
|
60
|
-
|
|
66
|
+
const ids = Array.isArray(data.ids) ? data.ids : null;
|
|
67
|
+
return toWords.map((value, index) => {
|
|
68
|
+
if (value !== null) return value;
|
|
69
|
+
return ids === null || (ids[index] ?? null) !== null ? null : params.words[index];
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Re-polls queued words until ready or the deadline, then returns null for
|
|
73
|
+
* the rest. A failed request leaves its words queued for the next round, so
|
|
74
|
+
* one error never discards what was already received. */
|
|
75
|
+
async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
|
|
76
|
+
const results = new Array(params.words.length).fill(null);
|
|
77
|
+
let pending = params.words.map((_, index) => index);
|
|
78
|
+
let received = false;
|
|
79
|
+
let lastError;
|
|
80
|
+
while (true) {
|
|
81
|
+
const stillPending = [];
|
|
82
|
+
for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {
|
|
83
|
+
const chunk = pending.slice(i, i + MAX_WORDS_PER_REQUEST);
|
|
84
|
+
try {
|
|
85
|
+
const translated = await require_timeout.withTimeout(this.translate({
|
|
86
|
+
from: params.from,
|
|
87
|
+
to: params.to,
|
|
88
|
+
words: chunk.map((index) => params.words[index]),
|
|
89
|
+
types: params.types && chunk.map((index) => params.types[index])
|
|
90
|
+
}), require_timeout.DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
|
|
91
|
+
received = true;
|
|
92
|
+
chunk.forEach((index, k) => {
|
|
93
|
+
if (translated[k] === null) stillPending.push(index);
|
|
94
|
+
else results[index] = translated[k];
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error instanceof UnsupportedLanguagePairError) throw error;
|
|
98
|
+
lastError = error;
|
|
99
|
+
stillPending.push(...chunk);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
pending = stillPending;
|
|
103
|
+
const remaining = deadline - Date.now();
|
|
104
|
+
if (pending.length === 0 || remaining <= 0) {
|
|
105
|
+
if (!received && lastError !== void 0) throw lastError;
|
|
106
|
+
return results;
|
|
107
|
+
}
|
|
108
|
+
await sleep(Math.min(pollIntervalMs, remaining));
|
|
109
|
+
}
|
|
61
110
|
}
|
|
62
111
|
async fetchSettings() {
|
|
63
|
-
const response = await require_timeout.withTimeout(fetch(
|
|
112
|
+
const response = await require_timeout.withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), require_timeout.DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
64
113
|
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
65
114
|
const data = await response.json();
|
|
115
|
+
if (data.product !== SUPPORTED_PRODUCT) throw new Error("@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.");
|
|
66
116
|
if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
|
|
67
117
|
const languages = data.languages.filter((lang) => lang.enabled !== false);
|
|
68
118
|
return {
|
|
69
119
|
sourceLocale: data.language_from,
|
|
70
120
|
targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
|
|
121
|
+
apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\/+$/, ""),
|
|
71
122
|
translationEngine: data.translation_engine,
|
|
72
123
|
apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
|
|
73
124
|
};
|
|
@@ -75,5 +126,6 @@ var WeglotApiClient = class {
|
|
|
75
126
|
};
|
|
76
127
|
|
|
77
128
|
//#endregion
|
|
129
|
+
exports.DEFAULT_API_BASE_URL = DEFAULT_API_BASE_URL;
|
|
78
130
|
exports.UnsupportedLanguagePairError = UnsupportedLanguagePairError;
|
|
79
131
|
exports.WeglotApiClient = WeglotApiClient;
|
|
@@ -3,25 +3,17 @@ import { WORD_TYPE } from "./definitions/definitions.generated.mjs";
|
|
|
3
3
|
|
|
4
4
|
//#region src/translators/weglot/api-client.ts
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* - Translation: POST https://api.weglot.com/translate?api_key=<key>
|
|
9
|
-
* - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,
|
|
10
|
-
* api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).
|
|
11
|
-
*
|
|
12
|
-
* Translations made through the API are recorded in the Weglot project and
|
|
13
|
-
* can be reviewed/edited in the Weglot dashboard.
|
|
6
|
+
* Weglot API client. Weglot translates with an LLM: a word not translated yet
|
|
7
|
+
* comes back null and is queued, so callers poll until it is ready.
|
|
14
8
|
*/
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const V1_KEY_PREFIX = "wg_";
|
|
9
|
+
const DEFAULT_SETTINGS_URL = "https://api.weglot.com/project-settings";
|
|
10
|
+
const DEFAULT_API_BASE_URL = "https://api.weglot.com";
|
|
11
|
+
const SUPPORTED_PRODUCT = "2.0";
|
|
19
12
|
const WORD_TYPE_TEXT = WORD_TYPE.TEXT;
|
|
20
13
|
const REQUEST_URL = "https://compiler.weglot.com/";
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
14
|
+
const WORD_LABEL = "translate-react";
|
|
15
|
+
const MAX_WORDS_PER_REQUEST = 100;
|
|
16
|
+
const DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
25
17
|
/** The API validates the pair independently of the project's languages, so
|
|
26
18
|
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
27
19
|
var UnsupportedLanguagePairError = class extends Error {
|
|
@@ -32,21 +24,34 @@ var UnsupportedLanguagePairError = class extends Error {
|
|
|
32
24
|
this.name = "UnsupportedLanguagePairError";
|
|
33
25
|
}
|
|
34
26
|
};
|
|
27
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
35
28
|
var WeglotApiClient = class {
|
|
36
|
-
|
|
29
|
+
apiBaseUrl;
|
|
30
|
+
constructor(apiKey, apiBaseUrl) {
|
|
37
31
|
this.apiKey = apiKey;
|
|
32
|
+
this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
|
|
38
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* One request. A word the API has queued comes back null; a word it will
|
|
36
|
+
* never translate comes back as its source text.
|
|
37
|
+
*/
|
|
39
38
|
async translate(params) {
|
|
40
|
-
const
|
|
39
|
+
const query = params.live ? "?live=1" : "";
|
|
40
|
+
const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
|
|
41
41
|
method: "POST",
|
|
42
|
-
headers: {
|
|
42
|
+
headers: {
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
Accept: "application/json",
|
|
45
|
+
Authorization: `Key ${this.apiKey}`
|
|
46
|
+
},
|
|
43
47
|
body: JSON.stringify({
|
|
44
48
|
l_from: params.from,
|
|
45
49
|
l_to: params.to,
|
|
46
50
|
request_url: REQUEST_URL,
|
|
47
51
|
words: params.words.map((w, index) => ({
|
|
48
52
|
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
49
|
-
w
|
|
53
|
+
w,
|
|
54
|
+
l: [WORD_LABEL]
|
|
50
55
|
}))
|
|
51
56
|
})
|
|
52
57
|
});
|
|
@@ -55,19 +60,65 @@ var WeglotApiClient = class {
|
|
|
55
60
|
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
56
61
|
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
57
62
|
}
|
|
58
|
-
const
|
|
63
|
+
const data = await response.json();
|
|
64
|
+
const toWords = data.to_words;
|
|
59
65
|
if (!Array.isArray(toWords) || toWords.length !== params.words.length) throw new Error(`Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : "none"})`);
|
|
60
|
-
|
|
66
|
+
const ids = Array.isArray(data.ids) ? data.ids : null;
|
|
67
|
+
return toWords.map((value, index) => {
|
|
68
|
+
if (value !== null) return value;
|
|
69
|
+
return ids === null || (ids[index] ?? null) !== null ? null : params.words[index];
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
/** Re-polls queued words until ready or the deadline, then returns null for
|
|
73
|
+
* the rest. A failed request leaves its words queued for the next round, so
|
|
74
|
+
* one error never discards what was already received. */
|
|
75
|
+
async translateUntilReady(params, { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }) {
|
|
76
|
+
const results = new Array(params.words.length).fill(null);
|
|
77
|
+
let pending = params.words.map((_, index) => index);
|
|
78
|
+
let received = false;
|
|
79
|
+
let lastError;
|
|
80
|
+
while (true) {
|
|
81
|
+
const stillPending = [];
|
|
82
|
+
for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {
|
|
83
|
+
const chunk = pending.slice(i, i + MAX_WORDS_PER_REQUEST);
|
|
84
|
+
try {
|
|
85
|
+
const translated = await withTimeout(this.translate({
|
|
86
|
+
from: params.from,
|
|
87
|
+
to: params.to,
|
|
88
|
+
words: chunk.map((index) => params.words[index]),
|
|
89
|
+
types: params.types && chunk.map((index) => params.types[index])
|
|
90
|
+
}), DEFAULT_TIMEOUTS.AI_API, `Weglot API translation to ${params.to}`);
|
|
91
|
+
received = true;
|
|
92
|
+
chunk.forEach((index, k) => {
|
|
93
|
+
if (translated[k] === null) stillPending.push(index);
|
|
94
|
+
else results[index] = translated[k];
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (error instanceof UnsupportedLanguagePairError) throw error;
|
|
98
|
+
lastError = error;
|
|
99
|
+
stillPending.push(...chunk);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
pending = stillPending;
|
|
103
|
+
const remaining = deadline - Date.now();
|
|
104
|
+
if (pending.length === 0 || remaining <= 0) {
|
|
105
|
+
if (!received && lastError !== void 0) throw lastError;
|
|
106
|
+
return results;
|
|
107
|
+
}
|
|
108
|
+
await sleep(Math.min(pollIntervalMs, remaining));
|
|
109
|
+
}
|
|
61
110
|
}
|
|
62
111
|
async fetchSettings() {
|
|
63
|
-
const response = await withTimeout(fetch(
|
|
112
|
+
const response = await withTimeout(fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, { headers: { Accept: "application/json" } }), DEFAULT_TIMEOUTS.AI_API, "Weglot project settings fetch");
|
|
64
113
|
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
65
114
|
const data = await response.json();
|
|
115
|
+
if (data.product !== SUPPORTED_PRODUCT) throw new Error("@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.");
|
|
66
116
|
if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
|
|
67
117
|
const languages = data.languages.filter((lang) => lang.enabled !== false);
|
|
68
118
|
return {
|
|
69
119
|
sourceLocale: data.language_from,
|
|
70
120
|
targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
|
|
121
|
+
apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\/+$/, ""),
|
|
71
122
|
translationEngine: data.translation_engine,
|
|
72
123
|
apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
|
|
73
124
|
};
|
|
@@ -75,5 +126,5 @@ var WeglotApiClient = class {
|
|
|
75
126
|
};
|
|
76
127
|
|
|
77
128
|
//#endregion
|
|
78
|
-
export { UnsupportedLanguagePairError, WeglotApiClient };
|
|
129
|
+
export { DEFAULT_API_BASE_URL, UnsupportedLanguagePairError, WeglotApiClient };
|
|
79
130
|
//# sourceMappingURL=api-client.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Thin HTTP client for the Weglot public API.\n *\n * - Translation: POST https://api.weglot.com/translate?api_key=<key>\n * - Project settings: cdn.weglot.com/projects-settings/<id>.json for v1 keys,\n * api.weglot.com/project-settings otherwise (weglot-js getCdnSettings.ts).\n *\n * Translations made through the API are recorded in the Weglot project and\n * can be reviewed/edited in the Weglot dashboard.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst TRANSLATE_URL = \"https://api.weglot.com/translate\";\nconst CDN_SETTINGS_URL = \"https://cdn.weglot.com/projects-settings\";\nconst API_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\n// v1 keys are the project id behind a \"wg_\" prefix; the CDN is keyed by the id.\nconst V1_KEY_PREFIX = \"wg_\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** Inline elements allowed in a segment; absent on older projects, then derived\n * from the key length. */\n translationEngine?: number;\n};\n\nexport function settingsUrlFor(apiKey: string): string {\n if (apiKey.startsWith(V1_KEY_PREFIX)) {\n return `${CDN_SETTINGS_URL}/${apiKey.slice(V1_KEY_PREFIX.length)}.json`;\n }\n return `${API_SETTINGS_URL}?api_key=${apiKey}`;\n}\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\nexport class WeglotApiClient {\n constructor(private readonly apiKey: string) {}\n\n async translate(params: {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n }): Promise<string[]> {\n const response = await fetch(\n `${TRANSLATE_URL}?api_key=${this.apiKey}`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n w,\n })),\n }),\n },\n );\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as { to_words?: string[] };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n return toWords;\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n fetch(settingsUrlFor(this.apiKey)),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n ),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,gBAAgB;AACtB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAEzB,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB,UAAU;AAEjC,MAAM,cAAc;AAapB,SAAgB,eAAe,QAAwB;AACrD,KAAI,OAAO,WAAW,cAAc,CAClC,QAAO,GAAG,iBAAiB,GAAG,OAAO,MAAM,EAAqB,CAAC;AAEnE,QAAO,GAAG,iBAAiB,WAAW;;;;AAKxC,IAAa,+BAAb,cAAkD,MAAM;CACtD,YACE,AAASA,MACT,AAASC,IACT;AACA,QAAM,sCAAsC,KAAK,QAAQ,GAAG,IAAI;EAHvD;EACA;AAGT,OAAK,OAAO;;;AAIhB,IAAa,kBAAb,MAA6B;CAC3B,YAAY,AAAiBC,QAAgB;EAAhB;;CAE7B,MAAM,UAAU,QAMM;EACpB,MAAM,WAAW,MAAM,MACrB,GAAG,cAAc,WAAW,KAAK,UACjC;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,KAAK,UAAU;IACnB,QAAQ,OAAO;IACf,MAAM,OAAO;IACb,aAAa;IACb,OAAO,OAAO,MAAM,KAAK,GAAG,WAAW;KACrC,GAAG,OAAO,QAAQ,UAAU;KAC5B;KACD,EAAE;IACJ,CAAC;GACH,CACF;AAED,MAAI,CAAC,SAAS,IAAI;GAChB,MAAM,OAAO,MAAM,SAAS,MAAM,CAAC,YAAY,GAAG;AAClD,OAAI,SAAS,WAAW,OAAO,4BAA4B,KAAK,KAAK,CACnE,OAAM,IAAI,6BAA6B,OAAO,MAAM,OAAO,GAAG;AAEhE,SAAM,IAAI,MACR,+BAA+B,SAAS,OAAO,KAAK,QAAQ,qBAC7D;;EAIH,MAAM,WADQ,MAAM,SAAS,MAAM,EACd;AACrB,MAAI,CAAC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,WAAW,OAAO,MAAM,OAC7D,OAAM,IAAI,MACR,+DAA+D,OAAO,MAAM,OAAO,aAAa,MAAM,QAAQ,QAAQ,GAAG,QAAQ,SAAS,OAAO,GAClJ;AAEH,SAAO;;CAGT,MAAM,gBAAgD;EACpD,MAAM,WAAW,MAAM,YACrB,MAAM,eAAe,KAAK,OAAO,CAAC,EAClC,iBAAiB,QACjB,gCACD;AAED,MAAI,CAAC,SAAS,GACZ,OAAM,IAAI,MACR,4CAA4C,SAAS,OAAO,iDAC7D;EAGH,MAAM,OAAQ,MAAM,SAAS,MAAM;AAUnC,MAAI,CAAC,KAAK,iBAAiB,CAAC,MAAM,QAAQ,KAAK,UAAU,CACvD,OAAM,IAAI,MACR,iFACD;EAIH,MAAM,YAAY,KAAK,UAAU,QAAQ,SAAS,KAAK,YAAY,MAAM;AAEzE,SAAO;GACL,cAAc,KAAK;GACnB,eAAe,UAAU,KAAK,SAAS,KAAK,eAAe,KAAK,YAAY;GAC5E,mBAAmB,KAAK;GACxB,YAAY,OAAO,YACjB,UAAU,KAAK,SAAS,CACtB,KAAK,eAAe,KAAK,aACzB,KAAK,YACN,CAAC,CACH;GACF"}
|
|
1
|
+
{"version":3,"file":"api-client.mjs","names":["from: string","to: string","apiKey: string","results: (string | null)[]","lastError: unknown","stillPending: number[]"],"sources":["../../../src/translators/weglot/api-client.ts"],"sourcesContent":["/**\n * Weglot API client. Weglot translates with an LLM: a word not translated yet\n * comes back null and is queued, so callers poll until it is ready.\n */\n\nimport { DEFAULT_TIMEOUTS, withTimeout } from \"../../utils/timeout\";\nimport { WORD_TYPE } from \"./definitions/definitions.generated\";\n\nconst DEFAULT_SETTINGS_URL = \"https://api.weglot.com/project-settings\";\nexport const DEFAULT_API_BASE_URL = \"https://api.weglot.com\";\nconst SUPPORTED_PRODUCT = \"2.0\";\n// Body text; other types identify attributes (VALUE, IMG_ALT) and would misfile it.\nconst WORD_TYPE_TEXT = WORD_TYPE.TEXT;\n// The API requires a request_url identifying the caller.\nconst REQUEST_URL = \"https://compiler.weglot.com/\";\n// Tags the words in the dashboard with where they came from.\nconst WORD_LABEL = \"translate-react\";\nexport const MAX_WORDS_PER_REQUEST = 100;\nexport const DEFAULT_POLL_INTERVAL_MS = 5_000;\n\nexport type WeglotProjectSettings = {\n sourceLocale: string;\n targetLocales: string[];\n /** Public locale to the code the translate API expects: `a0` is served as `br`,\n * and only `a0` is a valid pair. */\n apiLocales: Record<string, string>;\n /** The project's regional API host, e.g. https://eu.api.weglot.com. */\n apiBaseUrl: string;\n /** Inline elements allowed in a segment; absent on older projects. */\n translationEngine?: number;\n};\n\nexport type TranslateParams = {\n from: string;\n to: string;\n words: string[];\n /** Word type per word; body text when omitted. */\n types?: number[];\n /** Marks a request made while a page renders, as opposed to a build. */\n live?: boolean;\n};\n\nexport type PollOptions = {\n /** Epoch ms after which words still queued are given up on. */\n deadline: number;\n pollIntervalMs?: number;\n sleep?: (ms: number) => Promise<void>;\n};\n\n/** The API validates the pair independently of the project's languages, so\n * `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */\nexport class UnsupportedLanguagePairError extends Error {\n constructor(\n readonly from: string,\n readonly to: string,\n ) {\n super(`The Weglot API does not translate \"${from}\" to \"${to}\".`);\n this.name = \"UnsupportedLanguagePairError\";\n }\n}\n\nconst defaultSleep = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nexport class WeglotApiClient {\n private readonly apiBaseUrl: string;\n\n constructor(\n private readonly apiKey: string,\n apiBaseUrl?: string,\n ) {\n this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;\n }\n\n /**\n * One request. A word the API has queued comes back null; a word it will\n * never translate comes back as its source text.\n */\n async translate(params: TranslateParams): Promise<(string | null)[]> {\n const query = params.live ? \"?live=1\" : \"\";\n const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n Authorization: `Key ${this.apiKey}`,\n },\n body: JSON.stringify({\n l_from: params.from,\n l_to: params.to,\n request_url: REQUEST_URL,\n words: params.words.map((w, index) => ({\n t: params.types?.[index] ?? WORD_TYPE_TEXT,\n w,\n l: [WORD_LABEL],\n })),\n }),\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => \"\");\n if (response.status === 400 && /not valid languages pair/i.test(body)) {\n throw new UnsupportedLanguagePairError(params.from, params.to);\n }\n throw new Error(\n `Weglot translate API error (${response.status}): ${body || \"no response body\"}`,\n );\n }\n\n const data = (await response.json()) as {\n to_words?: (string | null)[];\n ids?: (string | null)[];\n };\n const toWords = data.to_words;\n if (!Array.isArray(toWords) || toWords.length !== params.words.length) {\n throw new Error(\n `Weglot translate API returned a mismatched word count (sent ${params.words.length}, received ${Array.isArray(toWords) ? toWords.length : \"none\"})`,\n );\n }\n const ids = Array.isArray(data.ids) ? data.ids : null;\n\n return toWords.map((value, index) => {\n if (value !== null) return value;\n // Null without an id was not queued: it will never be translated.\n const queued = ids === null || (ids[index] ?? null) !== null;\n return queued ? null : params.words[index];\n });\n }\n\n /** Re-polls queued words until ready or the deadline, then returns null for\n * the rest. A failed request leaves its words queued for the next round, so\n * one error never discards what was already received. */\n async translateUntilReady(\n params: TranslateParams,\n { deadline, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, sleep = defaultSleep }: PollOptions,\n ): Promise<(string | null)[]> {\n const results: (string | null)[] = new Array(params.words.length).fill(null);\n let pending = params.words.map((_, index) => index);\n let received = false;\n let lastError: unknown;\n\n while (true) {\n const stillPending: number[] = [];\n for (let i = 0; i < pending.length; i += MAX_WORDS_PER_REQUEST) {\n const chunk = pending.slice(i, i + MAX_WORDS_PER_REQUEST);\n try {\n const translated = await withTimeout(\n this.translate({\n from: params.from,\n to: params.to,\n words: chunk.map((index) => params.words[index]),\n types: params.types && chunk.map((index) => params.types![index]),\n }),\n DEFAULT_TIMEOUTS.AI_API,\n `Weglot API translation to ${params.to}`,\n );\n received = true;\n chunk.forEach((index, k) => {\n if (translated[k] === null) stillPending.push(index);\n else results[index] = translated[k];\n });\n } catch (error) {\n if (error instanceof UnsupportedLanguagePairError) throw error;\n lastError = error;\n stillPending.push(...chunk);\n }\n }\n pending = stillPending;\n\n const remaining = deadline - Date.now();\n if (pending.length === 0 || remaining <= 0) {\n // Nothing ever got through: a key or quota problem, not a slow queue.\n if (!received && lastError !== undefined) throw lastError;\n return results;\n }\n await sleep(Math.min(pollIntervalMs, remaining));\n }\n }\n\n async fetchSettings(): Promise<WeglotProjectSettings> {\n const response = await withTimeout(\n // Overridable to point at another settings endpoint.\n fetch(`${process.env.WEGLOT_SETTINGS_URL || DEFAULT_SETTINGS_URL}?api_key=${encodeURIComponent(this.apiKey)}`, {\n headers: { Accept: \"application/json\" },\n }),\n DEFAULT_TIMEOUTS.AI_API,\n \"Weglot project settings fetch\",\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`,\n );\n }\n\n const data = (await response.json()) as {\n product?: string;\n api_base_url?: string;\n language_from?: string;\n languages?: {\n language_to: string;\n custom_code?: string | null;\n enabled?: boolean;\n }[];\n translation_engine?: number;\n };\n\n if (data.product !== SUPPORTED_PRODUCT) {\n throw new Error(\n \"@weglot/translate-react does not support the Weglot project this key belongs to. Check that you are using the right project key.\",\n );\n }\n\n if (!data.language_from || !Array.isArray(data.languages)) {\n throw new Error(\n \"Unexpected Weglot project settings format: missing language_from or languages.\",\n );\n }\n\n // Disabled languages are not public, so they are not built.\n const languages = data.languages.filter((lang) => lang.enabled !== false);\n\n return {\n sourceLocale: data.language_from,\n targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),\n apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\\/+$/, \"\"),\n translationEngine: data.translation_engine,\n apiLocales: Object.fromEntries(\n languages.map((lang) => [\n lang.custom_code || lang.language_to,\n lang.language_to,\n ]),\n ),\n };\n }\n}\n"],"mappings":"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"}
|
|
@@ -5,11 +5,8 @@ const require_definitions_generated = require('./definitions/definitions.generat
|
|
|
5
5
|
* The engine version and the inline tags it merges: sending a tag it does not
|
|
6
6
|
* merge gets the segment back untranslated, so the set follows the project.
|
|
7
7
|
*/
|
|
8
|
-
/** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */
|
|
9
|
-
const V1_KEY_LENGTH = 36;
|
|
10
8
|
/** connect-edge's default for a modern key. weglot-js still defaults to 2. */
|
|
11
9
|
const DEFAULT_MODERN_ENGINE = 3;
|
|
12
|
-
const LEGACY_ENGINE = 1;
|
|
13
10
|
/** Fallback tag for a placeholder or unknown element; the name is only a hint,
|
|
14
11
|
* so the first permitted one wins. */
|
|
15
12
|
const FALLBACK_TAG_PREFERENCE = [
|
|
@@ -18,9 +15,9 @@ const FALLBACK_TAG_PREFERENCE = [
|
|
|
18
15
|
"u",
|
|
19
16
|
"b"
|
|
20
17
|
];
|
|
21
|
-
function resolveTranslationEngine(
|
|
18
|
+
function resolveTranslationEngine(fromSettings) {
|
|
22
19
|
if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
|
|
23
|
-
return
|
|
20
|
+
return DEFAULT_MODERN_ENGINE;
|
|
24
21
|
}
|
|
25
22
|
function mergeableTagsFor(engine) {
|
|
26
23
|
const tags = [];
|
|
@@ -5,11 +5,8 @@ import { MERGE_NODES } from "./definitions/definitions.generated.mjs";
|
|
|
5
5
|
* The engine version and the inline tags it merges: sending a tag it does not
|
|
6
6
|
* merge gets the segment back untranslated, so the set follows the project.
|
|
7
7
|
*/
|
|
8
|
-
/** Keys shorter than this are v1 projects, as connect-edge and weglot-js also detect. */
|
|
9
|
-
const V1_KEY_LENGTH = 36;
|
|
10
8
|
/** connect-edge's default for a modern key. weglot-js still defaults to 2. */
|
|
11
9
|
const DEFAULT_MODERN_ENGINE = 3;
|
|
12
|
-
const LEGACY_ENGINE = 1;
|
|
13
10
|
/** Fallback tag for a placeholder or unknown element; the name is only a hint,
|
|
14
11
|
* so the first permitted one wins. */
|
|
15
12
|
const FALLBACK_TAG_PREFERENCE = [
|
|
@@ -18,9 +15,9 @@ const FALLBACK_TAG_PREFERENCE = [
|
|
|
18
15
|
"u",
|
|
19
16
|
"b"
|
|
20
17
|
];
|
|
21
|
-
function resolveTranslationEngine(
|
|
18
|
+
function resolveTranslationEngine(fromSettings) {
|
|
22
19
|
if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
|
|
23
|
-
return
|
|
20
|
+
return DEFAULT_MODERN_ENGINE;
|
|
24
21
|
}
|
|
25
22
|
function mergeableTagsFor(engine) {
|
|
26
23
|
const tags = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.mjs","names":["tags: string[]","INLINE_TAGS: ReadonlySet<string>"],"sources":["../../../src/translators/weglot/engine.ts"],"sourcesContent":["/**\n * The engine version and the inline tags it merges: sending a tag it does not\n * merge gets the segment back untranslated, so the set follows the project.\n */\n\nimport { MERGE_NODES } from \"./definitions/definitions.generated\";\n\n/**
|
|
1
|
+
{"version":3,"file":"engine.mjs","names":["tags: string[]","INLINE_TAGS: ReadonlySet<string>"],"sources":["../../../src/translators/weglot/engine.ts"],"sourcesContent":["/**\n * The engine version and the inline tags it merges: sending a tag it does not\n * merge gets the segment back untranslated, so the set follows the project.\n */\n\nimport { MERGE_NODES } from \"./definitions/definitions.generated\";\n\n/** connect-edge's default for a modern key. weglot-js still defaults to 2. */\nexport const DEFAULT_MODERN_ENGINE = 3;\n\n/** Fallback tag for a placeholder or unknown element; the name is only a hint,\n * so the first permitted one wins. */\nconst FALLBACK_TAG_PREFERENCE = [\"span\", \"bdi\", \"u\", \"b\"];\n\nexport function resolveTranslationEngine(fromSettings?: number | null): number {\n if (typeof fromSettings === \"number\" && Number.isFinite(fromSettings) && fromSettings > 0) {\n return fromSettings;\n }\n return DEFAULT_MODERN_ENGINE;\n}\n\nexport function mergeableTagsFor(engine: number): ReadonlySet<string> {\n const tags: string[] = [];\n if (engine >= 2) tags.push(...MERGE_NODES.v2);\n if (engine > 2) tags.push(...MERGE_NODES.v3);\n return new Set(tags.map((tag) => tag.toLowerCase()));\n}\n\n/** Undefined on engine 1, which merges nothing and so permits no tag at all. */\nexport function fallbackWireTagFor(\n tags: ReadonlySet<string>,\n): string | undefined {\n return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));\n}\n\n/**\n * Every inline tag any engine merges. Fixed rather than per-project: the hash\n * follows the stored text, so a remote setting would re-hash on every change.\n */\nexport const INLINE_TAGS: ReadonlySet<string> = new Set(\n Object.values(MERGE_NODES)\n .flat()\n .map((tag) => tag.toLowerCase()),\n);\n"],"mappings":";;;;;;;;AAQA,MAAa,wBAAwB;;;AAIrC,MAAM,0BAA0B;CAAC;CAAQ;CAAO;CAAK;CAAI;AAEzD,SAAgB,yBAAyB,cAAsC;AAC7E,KAAI,OAAO,iBAAiB,YAAY,OAAO,SAAS,aAAa,IAAI,eAAe,EACtF,QAAO;AAET,QAAO;;AAGT,SAAgB,iBAAiB,QAAqC;CACpE,MAAMA,OAAiB,EAAE;AACzB,KAAI,UAAU,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC7C,KAAI,SAAS,EAAG,MAAK,KAAK,GAAG,YAAY,GAAG;AAC5C,QAAO,IAAI,IAAI,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC,CAAC;;;AAItD,SAAgB,mBACd,MACoB;AACpB,QAAO,wBAAwB,MAAM,QAAQ,KAAK,IAAI,IAAI,CAAC;;;;;;AAO7D,MAAaC,cAAmC,IAAI,IAClD,OAAO,OAAO,YAAY,CACvB,MAAM,CACN,KAAK,QAAQ,IAAI,aAAa,CAAC,CACnC"}
|
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
const require_timeout = require('../../utils/timeout.cjs');
|
|
2
1
|
const require_api_client = require('./api-client.cjs');
|
|
3
2
|
const require_engine = require('./engine.cjs');
|
|
4
3
|
const require_wire_format = require('./wire-format.cjs');
|
|
5
4
|
|
|
6
5
|
//#region src/translators/weglot/translator.ts
|
|
7
|
-
const MAX_WORDS_PER_REQUEST = 100;
|
|
8
6
|
var WeglotTranslator = class {
|
|
9
7
|
client;
|
|
10
8
|
engine;
|
|
11
|
-
constructor(config, logger, client) {
|
|
9
|
+
constructor(config, logger, client, pollOptions = {}) {
|
|
12
10
|
this.config = config;
|
|
13
11
|
this.logger = logger;
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
12
|
+
this.pollOptions = pollOptions;
|
|
13
|
+
this.client = client ?? new require_api_client.WeglotApiClient(config.apiKey, config.apiBaseUrl);
|
|
14
|
+
this.engine = require_engine.resolveTranslationEngine(config.translationEngine);
|
|
16
15
|
}
|
|
17
16
|
async translate(locale, entriesMap) {
|
|
18
17
|
const hashes = Object.keys(entriesMap);
|
|
@@ -33,26 +32,33 @@ var WeglotTranslator = class {
|
|
|
33
32
|
restore
|
|
34
33
|
});
|
|
35
34
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
this.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
35
|
+
if (protectedEntries.length === 0) return translations;
|
|
36
|
+
const translated = await this.client.translateUntilReady({
|
|
37
|
+
from: this.config.sourceLocale,
|
|
38
|
+
to: this.config.apiLocales?.[locale] ?? locale,
|
|
39
|
+
words: protectedEntries.map((entry) => entry.text)
|
|
40
|
+
}, {
|
|
41
|
+
...this.pollOptions,
|
|
42
|
+
deadline: Date.now() + this.config.translationTimeoutMs
|
|
43
|
+
});
|
|
44
|
+
let queued = 0;
|
|
45
|
+
protectedEntries.forEach((entry, index) => {
|
|
46
|
+
const result = translated[index];
|
|
47
|
+
const sourceText = entriesMap[entry.hash].text;
|
|
48
|
+
if (result === null) {
|
|
49
|
+
queued++;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const { text: restored, damaged } = entry.restore(result);
|
|
53
|
+
if (damaged) {
|
|
54
|
+
this.logger.warn(`Weglot translation for hash "${entry.hash}" (locale "${locale}") lost an interpolation or element during restore; falling back to source text.`);
|
|
55
|
+
translations[entry.hash] = sourceText;
|
|
56
|
+
} else if (result === entry.text && entry.text !== sourceText) {
|
|
57
|
+
this.logger.warn(`Weglot API returned hash "${entry.hash}" (locale "${locale}") untranslated; falling back to source text.`);
|
|
58
|
+
translations[entry.hash] = sourceText;
|
|
59
|
+
} else translations[entry.hash] = restored;
|
|
60
|
+
});
|
|
61
|
+
if (queued > 0) this.logger.warn(`${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1e3)}s. Translations already received are cached, so running again picks up the rest.`);
|
|
56
62
|
return translations;
|
|
57
63
|
}
|
|
58
64
|
};
|
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
import { DEFAULT_TIMEOUTS, withTimeout } from "../../utils/timeout.mjs";
|
|
2
1
|
import { WeglotApiClient } from "./api-client.mjs";
|
|
3
2
|
import { resolveTranslationEngine } from "./engine.mjs";
|
|
4
3
|
import { encodeForApi } from "./wire-format.mjs";
|
|
5
4
|
|
|
6
5
|
//#region src/translators/weglot/translator.ts
|
|
7
|
-
const MAX_WORDS_PER_REQUEST = 100;
|
|
8
6
|
var WeglotTranslator = class {
|
|
9
7
|
client;
|
|
10
8
|
engine;
|
|
11
|
-
constructor(config, logger, client) {
|
|
9
|
+
constructor(config, logger, client, pollOptions = {}) {
|
|
12
10
|
this.config = config;
|
|
13
11
|
this.logger = logger;
|
|
14
|
-
this.
|
|
15
|
-
this.
|
|
12
|
+
this.pollOptions = pollOptions;
|
|
13
|
+
this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);
|
|
14
|
+
this.engine = resolveTranslationEngine(config.translationEngine);
|
|
16
15
|
}
|
|
17
16
|
async translate(locale, entriesMap) {
|
|
18
17
|
const hashes = Object.keys(entriesMap);
|
|
@@ -33,26 +32,33 @@ var WeglotTranslator = class {
|
|
|
33
32
|
restore
|
|
34
33
|
});
|
|
35
34
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
this.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
35
|
+
if (protectedEntries.length === 0) return translations;
|
|
36
|
+
const translated = await this.client.translateUntilReady({
|
|
37
|
+
from: this.config.sourceLocale,
|
|
38
|
+
to: this.config.apiLocales?.[locale] ?? locale,
|
|
39
|
+
words: protectedEntries.map((entry) => entry.text)
|
|
40
|
+
}, {
|
|
41
|
+
...this.pollOptions,
|
|
42
|
+
deadline: Date.now() + this.config.translationTimeoutMs
|
|
43
|
+
});
|
|
44
|
+
let queued = 0;
|
|
45
|
+
protectedEntries.forEach((entry, index) => {
|
|
46
|
+
const result = translated[index];
|
|
47
|
+
const sourceText = entriesMap[entry.hash].text;
|
|
48
|
+
if (result === null) {
|
|
49
|
+
queued++;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const { text: restored, damaged } = entry.restore(result);
|
|
53
|
+
if (damaged) {
|
|
54
|
+
this.logger.warn(`Weglot translation for hash "${entry.hash}" (locale "${locale}") lost an interpolation or element during restore; falling back to source text.`);
|
|
55
|
+
translations[entry.hash] = sourceText;
|
|
56
|
+
} else if (result === entry.text && entry.text !== sourceText) {
|
|
57
|
+
this.logger.warn(`Weglot API returned hash "${entry.hash}" (locale "${locale}") untranslated; falling back to source text.`);
|
|
58
|
+
translations[entry.hash] = sourceText;
|
|
59
|
+
} else translations[entry.hash] = restored;
|
|
60
|
+
});
|
|
61
|
+
if (queued > 0) this.logger.warn(`${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1e3)}s. Translations already received are cached, so running again picks up the rest.`);
|
|
56
62
|
return translations;
|
|
57
63
|
}
|
|
58
64
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","translations: Record<string, string>","protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[]"],"sources":["../../../src/translators/weglot/translator.ts"],"sourcesContent":["import type { LocaleCode } from \"../../locale\";\nimport type { TranslatableEntry, Translator } from \"../api\";\nimport type { Logger } from \"../../utils/logger\";\nimport {
|
|
1
|
+
{"version":3,"file":"translator.mjs","names":["config: WeglotTranslatorConfig","logger: Logger","pollOptions: Omit<PollOptions, \"deadline\">","translations: Record<string, string>","protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[]"],"sources":["../../../src/translators/weglot/translator.ts"],"sourcesContent":["import type { LocaleCode } from \"../../locale\";\nimport type { TranslatableEntry, Translator } from \"../api\";\nimport type { Logger } from \"../../utils/logger\";\nimport { type PollOptions, WeglotApiClient } from \"./api-client\";\nimport { encodeForApi, type RestoredTranslation } from \"./wire-format\";\nimport { resolveTranslationEngine } from \"./engine\";\n\nexport interface WeglotTranslatorConfig {\n apiKey: string;\n sourceLocale: LocaleCode;\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n /** How long to wait for queued translations before leaving them out. */\n translationTimeoutMs: number;\n}\n\nexport class WeglotTranslator implements Translator<WeglotTranslatorConfig> {\n private readonly client: WeglotApiClient;\n private readonly engine: number;\n\n constructor(\n readonly config: WeglotTranslatorConfig,\n private readonly logger: Logger,\n client?: WeglotApiClient,\n private readonly pollOptions: Omit<PollOptions, \"deadline\"> = {},\n ) {\n this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);\n this.engine = resolveTranslationEngine(config.translationEngine);\n }\n\n async translate(\n locale: LocaleCode,\n entriesMap: Record<string, TranslatableEntry>,\n ): Promise<Record<string, string>> {\n const hashes = Object.keys(entriesMap);\n this.logger.debug(\n `Weglot translate() called for ${locale} with ${hashes.length} entries`,\n );\n\n const translations: Record<string, string> = {};\n const protectedEntries: {\n hash: string;\n text: string;\n restore: (translated: string) => RestoredTranslation;\n }[] = [];\n\n for (const hash of hashes) {\n const sourceText = entriesMap[hash].text;\n const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);\n if (!encodable) {\n // Engine 1 merges nothing, so markup cannot survive the wire form.\n this.logger.warn(\n `Weglot translation engine ${this.engine} cannot carry the markup in hash \"${hash}\"; falling back to source text.`,\n );\n translations[hash] = sourceText;\n continue;\n }\n protectedEntries.push({ hash, text: wire, restore });\n }\n\n if (protectedEntries.length === 0) return translations;\n\n const translated = await this.client.translateUntilReady(\n {\n from: this.config.sourceLocale,\n to: this.config.apiLocales?.[locale] ?? locale,\n words: protectedEntries.map((entry) => entry.text),\n },\n {\n ...this.pollOptions,\n deadline: Date.now() + this.config.translationTimeoutMs,\n },\n );\n\n let queued = 0;\n protectedEntries.forEach((entry, index) => {\n const result = translated[index];\n const sourceText = entriesMap[entry.hash].text;\n\n if (result === null) {\n // Left out rather than filled with source, which would be cached.\n queued++;\n return;\n }\n\n const { text: restored, damaged } = entry.restore(result);\n if (damaged) {\n this.logger.warn(\n `Weglot translation for hash \"${entry.hash}\" (locale \"${locale}\") lost an interpolation or element during restore; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else if (result === entry.text && entry.text !== sourceText) {\n // The API echoes a segment back verbatim when it rejects its markup.\n this.logger.warn(\n `Weglot API returned hash \"${entry.hash}\" (locale \"${locale}\") untranslated; falling back to source text.`,\n );\n translations[entry.hash] = sourceText;\n } else {\n translations[entry.hash] = restored;\n }\n });\n\n if (queued > 0) {\n this.logger.warn(\n `${queued} ${locale} translation(s) are still being generated by Weglot after ${Math.round(this.config.translationTimeoutMs / 1000)}s. Translations already received are cached, so running again picks up the rest.`,\n );\n }\n\n return translations;\n }\n}\n"],"mappings":";;;;;AAoBA,IAAa,mBAAb,MAA4E;CAC1E,AAAiB;CACjB,AAAiB;CAEjB,YACE,AAASA,QACT,AAAiBC,QACjB,QACA,AAAiBC,cAA6C,EAAE,EAChE;EAJS;EACQ;EAEA;AAEjB,OAAK,SAAS,UAAU,IAAI,gBAAgB,OAAO,QAAQ,OAAO,WAAW;AAC7E,OAAK,SAAS,yBAAyB,OAAO,kBAAkB;;CAGlE,MAAM,UACJ,QACA,YACiC;EACjC,MAAM,SAAS,OAAO,KAAK,WAAW;AACtC,OAAK,OAAO,MACV,iCAAiC,OAAO,QAAQ,OAAO,OAAO,UAC/D;EAED,MAAMC,eAAuC,EAAE;EAC/C,MAAMC,mBAIA,EAAE;AAER,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,aAAa,WAAW,MAAM;GACpC,MAAM,EAAE,MAAM,SAAS,cAAc,aAAa,YAAY,KAAK,OAAO;AAC1E,OAAI,CAAC,WAAW;AAEd,SAAK,OAAO,KACV,6BAA6B,KAAK,OAAO,oCAAoC,KAAK,iCACnF;AACD,iBAAa,QAAQ;AACrB;;AAEF,oBAAiB,KAAK;IAAE;IAAM,MAAM;IAAM;IAAS,CAAC;;AAGtD,MAAI,iBAAiB,WAAW,EAAG,QAAO;EAE1C,MAAM,aAAa,MAAM,KAAK,OAAO,oBACnC;GACE,MAAM,KAAK,OAAO;GAClB,IAAI,KAAK,OAAO,aAAa,WAAW;GACxC,OAAO,iBAAiB,KAAK,UAAU,MAAM,KAAK;GACnD,EACD;GACE,GAAG,KAAK;GACR,UAAU,KAAK,KAAK,GAAG,KAAK,OAAO;GACpC,CACF;EAED,IAAI,SAAS;AACb,mBAAiB,SAAS,OAAO,UAAU;GACzC,MAAM,SAAS,WAAW;GAC1B,MAAM,aAAa,WAAW,MAAM,MAAM;AAE1C,OAAI,WAAW,MAAM;AAEnB;AACA;;GAGF,MAAM,EAAE,MAAM,UAAU,YAAY,MAAM,QAAQ,OAAO;AACzD,OAAI,SAAS;AACX,SAAK,OAAO,KACV,gCAAgC,MAAM,KAAK,aAAa,OAAO,kFAChE;AACD,iBAAa,MAAM,QAAQ;cAClB,WAAW,MAAM,QAAQ,MAAM,SAAS,YAAY;AAE7D,SAAK,OAAO,KACV,6BAA6B,MAAM,KAAK,aAAa,OAAO,+CAC7D;AACD,iBAAa,MAAM,QAAQ;SAE3B,cAAa,MAAM,QAAQ;IAE7B;AAEF,MAAI,SAAS,EACX,MAAK,OAAO,KACV,GAAG,OAAO,GAAG,OAAO,4DAA4D,KAAK,MAAM,KAAK,OAAO,uBAAuB,IAAK,CAAC,kFACrI;AAGH,SAAO"}
|
package/build/types.d.cts
CHANGED
|
@@ -29,7 +29,7 @@ type LocalePersistenceConfig = {
|
|
|
29
29
|
* Fields that are resolved internally (from the Weglot project settings or the
|
|
30
30
|
* environment) rather than provided by users.
|
|
31
31
|
*/
|
|
32
|
-
type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "weglotDir";
|
|
32
|
+
type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "apiBaseUrl" | "weglotDir";
|
|
33
33
|
/**
|
|
34
34
|
* Configuration for @weglot/translate-react
|
|
35
35
|
*/
|
|
@@ -92,9 +92,19 @@ type WeglotConfig = {
|
|
|
92
92
|
/** Public locale to the code the translate API expects, for languages with a
|
|
93
93
|
* custom code. Resolved from the project settings. @internal */
|
|
94
94
|
apiLocales: Record<string, LocaleCode>;
|
|
95
|
-
/** Inline elements allowed inside a segment, from the project settings
|
|
96
|
-
*
|
|
95
|
+
/** Inline elements allowed inside a segment, from the project settings.
|
|
96
|
+
* @internal */
|
|
97
97
|
translationEngine: number;
|
|
98
|
+
/** The project's regional API host, from the project settings. @internal */
|
|
99
|
+
apiBaseUrl: string;
|
|
100
|
+
/**
|
|
101
|
+
* Seconds to wait for translations Weglot is still generating. What is still
|
|
102
|
+
* missing then fails a `translate` build; in dev it shows up on a reload.
|
|
103
|
+
* Can be overridden by WEGLOT_TRANSLATION_TIMEOUT environment variable.
|
|
104
|
+
*
|
|
105
|
+
* @default 300 in a build, 10 in dev
|
|
106
|
+
*/
|
|
107
|
+
translationTimeout: number;
|
|
98
108
|
/**
|
|
99
109
|
* Whether to require 'use i18n' directive
|
|
100
110
|
*/
|