@weglot/translate-react 0.0.0-stage → 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/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +199 -2
- package/build/_virtual/rolldown_runtime.cjs +29 -0
- package/build/_virtual/rolldown_runtime.mjs +7 -0
- package/build/index.cjs +0 -0
- package/build/index.d.cts +2 -0
- package/build/index.d.mts +2 -0
- package/build/index.mjs +1 -0
- package/build/locale.d.cts +6 -0
- package/build/locale.d.cts.map +1 -0
- package/build/locale.d.mts +6 -0
- package/build/locale.d.mts.map +1 -0
- package/build/metadata/manager.cjs +119 -0
- package/build/metadata/manager.mjs +114 -0
- package/build/metadata/manager.mjs.map +1 -0
- package/build/plugin/build-translator.cjs +210 -0
- package/build/plugin/build-translator.mjs +208 -0
- package/build/plugin/build-translator.mjs.map +1 -0
- package/build/plugin/cleanup.cjs +20 -0
- package/build/plugin/cleanup.mjs +20 -0
- package/build/plugin/cleanup.mjs.map +1 -0
- package/build/plugin/index.cjs +0 -0
- package/build/plugin/index.d.cts +2 -0
- package/build/plugin/index.d.mts +2 -0
- package/build/plugin/index.mjs +1 -0
- package/build/plugin/next-compiler-loader.cjs +40 -0
- package/build/plugin/next-compiler-loader.d.cts +12 -0
- package/build/plugin/next-compiler-loader.d.cts.map +1 -0
- package/build/plugin/next-compiler-loader.d.mts +13 -0
- package/build/plugin/next-compiler-loader.d.mts.map +1 -0
- package/build/plugin/next-compiler-loader.mjs +41 -0
- package/build/plugin/next-compiler-loader.mjs.map +1 -0
- package/build/plugin/next-config-loader.cjs +13 -0
- package/build/plugin/next-config-loader.d.cts +8 -0
- package/build/plugin/next-config-loader.d.cts.map +1 -0
- package/build/plugin/next-config-loader.d.mts +9 -0
- package/build/plugin/next-config-loader.d.mts.map +1 -0
- package/build/plugin/next-config-loader.mjs +14 -0
- package/build/plugin/next-config-loader.mjs.map +1 -0
- package/build/plugin/next-locale-client-loader.cjs +9 -0
- package/build/plugin/next-locale-client-loader.d.cts +8 -0
- package/build/plugin/next-locale-client-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-client-loader.d.mts +9 -0
- package/build/plugin/next-locale-client-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-client-loader.mjs +10 -0
- package/build/plugin/next-locale-client-loader.mjs.map +1 -0
- package/build/plugin/next-locale-server-loader.cjs +9 -0
- package/build/plugin/next-locale-server-loader.d.cts +8 -0
- package/build/plugin/next-locale-server-loader.d.cts.map +1 -0
- package/build/plugin/next-locale-server-loader.d.mts +9 -0
- package/build/plugin/next-locale-server-loader.d.mts.map +1 -0
- package/build/plugin/next-locale-server-loader.mjs +10 -0
- package/build/plugin/next-locale-server-loader.mjs.map +1 -0
- package/build/plugin/next.cjs +227 -0
- package/build/plugin/next.d.cts +9 -0
- package/build/plugin/next.d.cts.map +1 -0
- package/build/plugin/next.d.mts +9 -0
- package/build/plugin/next.d.mts.map +1 -0
- package/build/plugin/next.mjs +229 -0
- package/build/plugin/next.mjs.map +1 -0
- package/build/plugin/transform/babel-compat.cjs +13 -0
- package/build/plugin/transform/babel-compat.mjs +10 -0
- package/build/plugin/transform/babel-compat.mjs.map +1 -0
- package/build/plugin/transform/expression-strings.cjs +145 -0
- package/build/plugin/transform/expression-strings.mjs +140 -0
- package/build/plugin/transform/expression-strings.mjs.map +1 -0
- package/build/plugin/transform/index.cjs +45 -0
- package/build/plugin/transform/index.mjs +43 -0
- package/build/plugin/transform/index.mjs.map +1 -0
- package/build/plugin/transform/metadata.cjs +142 -0
- package/build/plugin/transform/metadata.mjs +141 -0
- package/build/plugin/transform/metadata.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +525 -0
- package/build/plugin/transform/process-file.mjs +524 -0
- package/build/plugin/transform/process-file.mjs.map +1 -0
- package/build/plugin/transform/use-i18n.cjs +8 -0
- package/build/plugin/transform/use-i18n.mjs +7 -0
- package/build/plugin/transform/use-i18n.mjs.map +1 -0
- package/build/plugin/transform/utils.cjs +237 -0
- package/build/plugin/transform/utils.mjs +219 -0
- package/build/plugin/transform/utils.mjs.map +1 -0
- package/build/plugin/unplugin.cjs +188 -0
- package/build/plugin/unplugin.d.cts +8 -0
- package/build/plugin/unplugin.d.cts.map +1 -0
- package/build/plugin/unplugin.d.mts +8 -0
- package/build/plugin/unplugin.d.mts.map +1 -0
- package/build/plugin/unplugin.mjs +188 -0
- package/build/plugin/unplugin.mjs.map +1 -0
- package/build/plugin/vite.cjs +27 -0
- package/build/plugin/vite.d.cts +9 -0
- package/build/plugin/vite.d.cts.map +1 -0
- package/build/plugin/vite.d.mts +9 -0
- package/build/plugin/vite.d.mts.map +1 -0
- package/build/plugin/vite.mjs +28 -0
- package/build/plugin/vite.mjs.map +1 -0
- package/build/plugin/webpack.cjs +26 -0
- package/build/plugin/webpack.d.cts +8 -0
- package/build/plugin/webpack.d.cts.map +1 -0
- package/build/plugin/webpack.d.mts +8 -0
- package/build/plugin/webpack.d.mts.map +1 -0
- package/build/plugin/webpack.mjs +27 -0
- package/build/plugin/webpack.mjs.map +1 -0
- package/build/react/client/index.cjs +9 -0
- package/build/react/client/index.d.cts +5 -0
- package/build/react/client/index.d.mts +5 -0
- package/build/react/client/index.mjs +6 -0
- package/build/react/client/useTranslation.cjs +71 -0
- package/build/react/client/useTranslation.d.cts +42 -0
- package/build/react/client/useTranslation.d.cts.map +1 -0
- package/build/react/client/useTranslation.d.mts +42 -0
- package/build/react/client/useTranslation.d.mts.map +1 -0
- package/build/react/client/useTranslation.mjs +71 -0
- package/build/react/client/useTranslation.mjs.map +1 -0
- package/build/react/next/client.cjs +25 -0
- package/build/react/next/client.d.cts +9 -0
- package/build/react/next/client.d.cts.map +1 -0
- package/build/react/next/client.d.mts +9 -0
- package/build/react/next/client.d.mts.map +1 -0
- package/build/react/next/client.mjs +24 -0
- package/build/react/next/client.mjs.map +1 -0
- package/build/react/next/cookie-locale-resolver.cjs +29 -0
- package/build/react/next/cookie-locale-resolver.d.cts +33 -0
- package/build/react/next/cookie-locale-resolver.d.cts.map +1 -0
- package/build/react/next/cookie-locale-resolver.d.mts +33 -0
- package/build/react/next/cookie-locale-resolver.d.mts.map +1 -0
- package/build/react/next/cookie-locale-resolver.mjs +29 -0
- package/build/react/next/cookie-locale-resolver.mjs.map +1 -0
- package/build/react/next/server.cjs +21 -0
- package/build/react/next/server.d.cts +13 -0
- package/build/react/next/server.d.cts.map +1 -0
- package/build/react/next/server.d.mts +14 -0
- package/build/react/next/server.d.mts.map +1 -0
- package/build/react/next/server.mjs +20 -0
- package/build/react/next/server.mjs.map +1 -0
- package/build/react/server/ServerWeglotProvider.cjs +19 -0
- package/build/react/server/ServerWeglotProvider.d.cts +12 -0
- package/build/react/server/ServerWeglotProvider.d.cts.map +1 -0
- package/build/react/server/ServerWeglotProvider.d.mts +12 -0
- package/build/react/server/ServerWeglotProvider.d.mts.map +1 -0
- package/build/react/server/ServerWeglotProvider.mjs +19 -0
- package/build/react/server/ServerWeglotProvider.mjs.map +1 -0
- package/build/react/server/index.cjs +7 -0
- package/build/react/server/index.d.cts +4 -0
- package/build/react/server/index.d.mts +4 -0
- package/build/react/server/index.mjs +5 -0
- package/build/react/server/useTranslation.cjs +60 -0
- package/build/react/server/useTranslation.d.cts +36 -0
- package/build/react/server/useTranslation.d.cts.map +1 -0
- package/build/react/server/useTranslation.d.mts +36 -0
- package/build/react/server/useTranslation.d.mts.map +1 -0
- package/build/react/server/useTranslation.mjs +60 -0
- package/build/react/server/useTranslation.mjs.map +1 -0
- package/build/react/server-only/index.cjs +42 -0
- package/build/react/server-only/index.d.cts +38 -0
- package/build/react/server-only/index.d.cts.map +1 -0
- package/build/react/server-only/index.d.mts +38 -0
- package/build/react/server-only/index.d.mts.map +1 -0
- package/build/react/server-only/index.mjs +42 -0
- package/build/react/server-only/index.mjs.map +1 -0
- package/build/react/server-only/translations.cjs +86 -0
- package/build/react/server-only/translations.mjs +86 -0
- package/build/react/server-only/translations.mjs.map +1 -0
- package/build/react/shared/LocaleSwitcher.cjs +61 -0
- package/build/react/shared/LocaleSwitcher.d.cts +71 -0
- package/build/react/shared/LocaleSwitcher.d.cts.map +1 -0
- package/build/react/shared/LocaleSwitcher.d.mts +71 -0
- package/build/react/shared/LocaleSwitcher.d.mts.map +1 -0
- package/build/react/shared/LocaleSwitcher.mjs +61 -0
- package/build/react/shared/LocaleSwitcher.mjs.map +1 -0
- package/build/react/shared/WeglotContext.cjs +14 -0
- package/build/react/shared/WeglotContext.d.cts +34 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -0
- package/build/react/shared/WeglotContext.d.mts +34 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -0
- package/build/react/shared/WeglotContext.mjs +13 -0
- package/build/react/shared/WeglotContext.mjs.map +1 -0
- package/build/react/shared/WeglotProvider.cjs +250 -0
- package/build/react/shared/WeglotProvider.d.cts +60 -0
- package/build/react/shared/WeglotProvider.d.cts.map +1 -0
- package/build/react/shared/WeglotProvider.d.mts +60 -0
- package/build/react/shared/WeglotProvider.d.mts.map +1 -0
- package/build/react/shared/WeglotProvider.mjs +250 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -0
- package/build/react/shared/render-rich-text.cjs +56 -0
- package/build/react/shared/render-rich-text.d.cts +16 -0
- package/build/react/shared/render-rich-text.d.cts.map +1 -0
- package/build/react/shared/render-rich-text.d.mts +16 -0
- package/build/react/shared/render-rich-text.d.mts.map +1 -0
- package/build/react/shared/render-rich-text.mjs +55 -0
- package/build/react/shared/render-rich-text.mjs.map +1 -0
- package/build/react/shared/utils.cjs +34 -0
- package/build/react/shared/utils.mjs +35 -0
- package/build/react/shared/utils.mjs.map +1 -0
- package/build/react/types.d.cts +16 -0
- package/build/react/types.d.cts.map +1 -0
- package/build/react/types.d.mts +16 -0
- package/build/react/types.d.mts.map +1 -0
- package/build/runtime/html/segmenter.cjs +226 -0
- package/build/runtime/html/segmenter.mjs +225 -0
- package/build/runtime/html/segmenter.mjs.map +1 -0
- package/build/runtime/index.cjs +6 -0
- package/build/runtime/index.d.cts +2 -0
- package/build/runtime/index.d.mts +2 -0
- package/build/runtime/index.mjs +3 -0
- package/build/runtime/translate-dynamic.cjs +144 -0
- package/build/runtime/translate-dynamic.d.cts +29 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -0
- package/build/runtime/translate-dynamic.d.mts +29 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -0
- package/build/runtime/translate-dynamic.mjs +141 -0
- package/build/runtime/translate-dynamic.mjs.map +1 -0
- package/build/translation-server/logger.cjs +37 -0
- package/build/translation-server/logger.mjs +37 -0
- package/build/translation-server/logger.mjs.map +1 -0
- package/build/translation-server/translation-server.cjs +451 -0
- package/build/translation-server/translation-server.mjs +448 -0
- package/build/translation-server/translation-server.mjs.map +1 -0
- package/build/translators/api.cjs +12 -0
- package/build/translators/api.mjs +12 -0
- package/build/translators/api.mjs.map +1 -0
- package/build/translators/cache-factory.cjs +26 -0
- package/build/translators/cache-factory.mjs +27 -0
- package/build/translators/cache-factory.mjs.map +1 -0
- package/build/translators/local-cache.cjs +132 -0
- package/build/translators/local-cache.mjs +130 -0
- package/build/translators/local-cache.mjs.map +1 -0
- package/build/translators/translation-service.cjs +139 -0
- package/build/translators/translation-service.mjs +140 -0
- package/build/translators/translation-service.mjs.map +1 -0
- package/build/translators/weglot/api-client.cjs +131 -0
- package/build/translators/weglot/api-client.mjs +130 -0
- package/build/translators/weglot/api-client.mjs.map +1 -0
- package/build/translators/weglot/definitions/definitions.generated.cjs +53 -0
- package/build/translators/weglot/definitions/definitions.generated.mjs +52 -0
- package/build/translators/weglot/definitions/definitions.generated.mjs.map +1 -0
- package/build/translators/weglot/engine.cjs +43 -0
- package/build/translators/weglot/engine.mjs +40 -0
- package/build/translators/weglot/engine.mjs.map +1 -0
- package/build/translators/weglot/translator.cjs +67 -0
- package/build/translators/weglot/translator.mjs +68 -0
- package/build/translators/weglot/translator.mjs.map +1 -0
- package/build/translators/weglot/wire-format.cjs +128 -0
- package/build/translators/weglot/wire-format.mjs +129 -0
- package/build/translators/weglot/wire-format.mjs.map +1 -0
- package/build/types.d.cts +153 -0
- package/build/types.d.cts.map +1 -0
- package/build/types.d.mts +153 -0
- package/build/types.d.mts.map +1 -0
- package/build/utils/config-factory.cjs +100 -0
- package/build/utils/config-factory.mjs +97 -0
- package/build/utils/config-factory.mjs.map +1 -0
- package/build/utils/hash.cjs +17 -0
- package/build/utils/hash.mjs +16 -0
- package/build/utils/hash.mjs.map +1 -0
- package/build/utils/is-valid-locale.cjs +13 -0
- package/build/utils/is-valid-locale.mjs +13 -0
- package/build/utils/is-valid-locale.mjs.map +1 -0
- package/build/utils/logger.cjs +51 -0
- package/build/utils/logger.mjs +50 -0
- package/build/utils/logger.mjs.map +1 -0
- package/build/utils/path-helpers.cjs +49 -0
- package/build/utils/path-helpers.mjs +47 -0
- package/build/utils/path-helpers.mjs.map +1 -0
- package/build/utils/timeout.cjs +42 -0
- package/build/utils/timeout.mjs +41 -0
- package/build/utils/timeout.mjs.map +1 -0
- package/build/virtual/code-generator.cjs +58 -0
- package/build/virtual/code-generator.mjs +57 -0
- package/build/virtual/code-generator.mjs.map +1 -0
- package/build/virtual/config.cjs +19 -0
- package/build/virtual/config.d.cts +15 -0
- package/build/virtual/config.d.cts.map +1 -0
- package/build/virtual/config.d.mts +15 -0
- package/build/virtual/config.d.mts.map +1 -0
- package/build/virtual/config.mjs +14 -0
- package/build/virtual/config.mjs.map +1 -0
- package/build/virtual/locale/client.cjs +23 -0
- package/build/virtual/locale/client.d.cts +19 -0
- package/build/virtual/locale/client.d.cts.map +1 -0
- package/build/virtual/locale/client.d.mts +19 -0
- package/build/virtual/locale/client.d.mts.map +1 -0
- package/build/virtual/locale/client.mjs +22 -0
- package/build/virtual/locale/client.mjs.map +1 -0
- package/build/virtual/locale/server.cjs +13 -0
- package/build/virtual/locale/server.d.cts +13 -0
- package/build/virtual/locale/server.d.cts.map +1 -0
- package/build/virtual/locale/server.d.mts +13 -0
- package/build/virtual/locale/server.d.mts.map +1 -0
- package/build/virtual/locale/server.mjs +13 -0
- package/build/virtual/locale/server.mjs.map +1 -0
- package/package.json +260 -4
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
const require_timeout = require('../../utils/timeout.cjs');
|
|
2
|
+
const require_definitions_generated = require('./definitions/definitions.generated.cjs');
|
|
3
|
+
|
|
4
|
+
//#region src/translators/weglot/api-client.ts
|
|
5
|
+
/**
|
|
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.
|
|
8
|
+
*/
|
|
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";
|
|
12
|
+
const WORD_TYPE_TEXT = require_definitions_generated.WORD_TYPE.TEXT;
|
|
13
|
+
const REQUEST_URL = "https://compiler.weglot.com/";
|
|
14
|
+
const WORD_LABEL = "translate-react";
|
|
15
|
+
const MAX_WORDS_PER_REQUEST = 100;
|
|
16
|
+
const DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
17
|
+
/** The API validates the pair independently of the project's languages, so
|
|
18
|
+
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
19
|
+
var UnsupportedLanguagePairError = class extends Error {
|
|
20
|
+
constructor(from, to) {
|
|
21
|
+
super(`The Weglot API does not translate "${from}" to "${to}".`);
|
|
22
|
+
this.from = from;
|
|
23
|
+
this.to = to;
|
|
24
|
+
this.name = "UnsupportedLanguagePairError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
28
|
+
var WeglotApiClient = class {
|
|
29
|
+
apiBaseUrl;
|
|
30
|
+
constructor(apiKey, apiBaseUrl) {
|
|
31
|
+
this.apiKey = apiKey;
|
|
32
|
+
this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
|
|
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
|
+
*/
|
|
38
|
+
async translate(params) {
|
|
39
|
+
const query = params.live ? "?live=1" : "";
|
|
40
|
+
const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
|
|
41
|
+
method: "POST",
|
|
42
|
+
headers: {
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
Accept: "application/json",
|
|
45
|
+
Authorization: `Key ${this.apiKey}`
|
|
46
|
+
},
|
|
47
|
+
body: JSON.stringify({
|
|
48
|
+
l_from: params.from,
|
|
49
|
+
l_to: params.to,
|
|
50
|
+
request_url: REQUEST_URL,
|
|
51
|
+
words: params.words.map((w, index) => ({
|
|
52
|
+
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
53
|
+
w,
|
|
54
|
+
l: [WORD_LABEL]
|
|
55
|
+
}))
|
|
56
|
+
})
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
const body = await response.text().catch(() => "");
|
|
60
|
+
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
61
|
+
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
62
|
+
}
|
|
63
|
+
const data = await response.json();
|
|
64
|
+
const toWords = data.to_words;
|
|
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"})`);
|
|
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
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async fetchSettings() {
|
|
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");
|
|
113
|
+
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
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.");
|
|
116
|
+
if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
|
|
117
|
+
const languages = data.languages.filter((lang) => lang.enabled !== false);
|
|
118
|
+
return {
|
|
119
|
+
sourceLocale: data.language_from,
|
|
120
|
+
targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
|
|
121
|
+
apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\/+$/, ""),
|
|
122
|
+
translationEngine: data.translation_engine,
|
|
123
|
+
apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
//#endregion
|
|
129
|
+
exports.DEFAULT_API_BASE_URL = DEFAULT_API_BASE_URL;
|
|
130
|
+
exports.UnsupportedLanguagePairError = UnsupportedLanguagePairError;
|
|
131
|
+
exports.WeglotApiClient = WeglotApiClient;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { DEFAULT_TIMEOUTS, withTimeout } from "../../utils/timeout.mjs";
|
|
2
|
+
import { WORD_TYPE } from "./definitions/definitions.generated.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/translators/weglot/api-client.ts
|
|
5
|
+
/**
|
|
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.
|
|
8
|
+
*/
|
|
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";
|
|
12
|
+
const WORD_TYPE_TEXT = WORD_TYPE.TEXT;
|
|
13
|
+
const REQUEST_URL = "https://compiler.weglot.com/";
|
|
14
|
+
const WORD_LABEL = "translate-react";
|
|
15
|
+
const MAX_WORDS_PER_REQUEST = 100;
|
|
16
|
+
const DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
17
|
+
/** The API validates the pair independently of the project's languages, so
|
|
18
|
+
* `en`→`sr-latn` can be refused. Callers skip the locale rather than failing. */
|
|
19
|
+
var UnsupportedLanguagePairError = class extends Error {
|
|
20
|
+
constructor(from, to) {
|
|
21
|
+
super(`The Weglot API does not translate "${from}" to "${to}".`);
|
|
22
|
+
this.from = from;
|
|
23
|
+
this.to = to;
|
|
24
|
+
this.name = "UnsupportedLanguagePairError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
28
|
+
var WeglotApiClient = class {
|
|
29
|
+
apiBaseUrl;
|
|
30
|
+
constructor(apiKey, apiBaseUrl) {
|
|
31
|
+
this.apiKey = apiKey;
|
|
32
|
+
this.apiBaseUrl = apiBaseUrl || DEFAULT_API_BASE_URL;
|
|
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
|
+
*/
|
|
38
|
+
async translate(params) {
|
|
39
|
+
const query = params.live ? "?live=1" : "";
|
|
40
|
+
const response = await fetch(`${this.apiBaseUrl}/translate${query}`, {
|
|
41
|
+
method: "POST",
|
|
42
|
+
headers: {
|
|
43
|
+
"Content-Type": "application/json",
|
|
44
|
+
Accept: "application/json",
|
|
45
|
+
Authorization: `Key ${this.apiKey}`
|
|
46
|
+
},
|
|
47
|
+
body: JSON.stringify({
|
|
48
|
+
l_from: params.from,
|
|
49
|
+
l_to: params.to,
|
|
50
|
+
request_url: REQUEST_URL,
|
|
51
|
+
words: params.words.map((w, index) => ({
|
|
52
|
+
t: params.types?.[index] ?? WORD_TYPE_TEXT,
|
|
53
|
+
w,
|
|
54
|
+
l: [WORD_LABEL]
|
|
55
|
+
}))
|
|
56
|
+
})
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
const body = await response.text().catch(() => "");
|
|
60
|
+
if (response.status === 400 && /not valid languages pair/i.test(body)) throw new UnsupportedLanguagePairError(params.from, params.to);
|
|
61
|
+
throw new Error(`Weglot translate API error (${response.status}): ${body || "no response body"}`);
|
|
62
|
+
}
|
|
63
|
+
const data = await response.json();
|
|
64
|
+
const toWords = data.to_words;
|
|
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"})`);
|
|
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
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async fetchSettings() {
|
|
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");
|
|
113
|
+
if (!response.ok) throw new Error(`Failed to fetch Weglot project settings (${response.status}). Check that your Weglot project key is valid.`);
|
|
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.");
|
|
116
|
+
if (!data.language_from || !Array.isArray(data.languages)) throw new Error("Unexpected Weglot project settings format: missing language_from or languages.");
|
|
117
|
+
const languages = data.languages.filter((lang) => lang.enabled !== false);
|
|
118
|
+
return {
|
|
119
|
+
sourceLocale: data.language_from,
|
|
120
|
+
targetLocales: languages.map((lang) => lang.custom_code || lang.language_to),
|
|
121
|
+
apiBaseUrl: (data.api_base_url || DEFAULT_API_BASE_URL).replace(/\/+$/, ""),
|
|
122
|
+
translationEngine: data.translation_engine,
|
|
123
|
+
apiLocales: Object.fromEntries(languages.map((lang) => [lang.custom_code || lang.language_to, lang.language_to]))
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
//#endregion
|
|
129
|
+
export { DEFAULT_API_BASE_URL, UnsupportedLanguagePairError, WeglotApiClient };
|
|
130
|
+
//# sourceMappingURL=api-client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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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"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/translators/weglot/definitions/definitions.generated.ts
|
|
3
|
+
/** Inline elements merged into the surrounding segment, by engine version. */
|
|
4
|
+
const MERGE_NODES = {
|
|
5
|
+
"v1": [],
|
|
6
|
+
"v2": [
|
|
7
|
+
"ABBR",
|
|
8
|
+
"ACRONYM",
|
|
9
|
+
"B",
|
|
10
|
+
"BDO",
|
|
11
|
+
"BIG",
|
|
12
|
+
"CITE",
|
|
13
|
+
"EM",
|
|
14
|
+
"I",
|
|
15
|
+
"KBD",
|
|
16
|
+
"Q",
|
|
17
|
+
"SMALL",
|
|
18
|
+
"STRONG",
|
|
19
|
+
"SUB",
|
|
20
|
+
"SUP",
|
|
21
|
+
"U"
|
|
22
|
+
],
|
|
23
|
+
"v3": [
|
|
24
|
+
"A",
|
|
25
|
+
"BDI",
|
|
26
|
+
"BR",
|
|
27
|
+
"WBR",
|
|
28
|
+
"DEL",
|
|
29
|
+
"DFN",
|
|
30
|
+
"INS",
|
|
31
|
+
"S",
|
|
32
|
+
"SPAN",
|
|
33
|
+
"MARK"
|
|
34
|
+
]
|
|
35
|
+
};
|
|
36
|
+
/** Weglot word types: what a translatable string is attached to. */
|
|
37
|
+
const WORD_TYPE = {
|
|
38
|
+
"OTHER": 0,
|
|
39
|
+
"TEXT": 1,
|
|
40
|
+
"VALUE": 2,
|
|
41
|
+
"PLACEHOLDER": 3,
|
|
42
|
+
"META_CONTENT": 4,
|
|
43
|
+
"IFRAME_SRC": 5,
|
|
44
|
+
"IMG_SRC": 6,
|
|
45
|
+
"IMG_ALT": 7,
|
|
46
|
+
"PDF_HREF": 8,
|
|
47
|
+
"PAGE_TITLE": 9,
|
|
48
|
+
"EXTERNAL_LINK": 10
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
//#endregion
|
|
52
|
+
exports.MERGE_NODES = MERGE_NODES;
|
|
53
|
+
exports.WORD_TYPE = WORD_TYPE;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
//#region src/translators/weglot/definitions/definitions.generated.ts
|
|
2
|
+
/** Inline elements merged into the surrounding segment, by engine version. */
|
|
3
|
+
const MERGE_NODES = {
|
|
4
|
+
"v1": [],
|
|
5
|
+
"v2": [
|
|
6
|
+
"ABBR",
|
|
7
|
+
"ACRONYM",
|
|
8
|
+
"B",
|
|
9
|
+
"BDO",
|
|
10
|
+
"BIG",
|
|
11
|
+
"CITE",
|
|
12
|
+
"EM",
|
|
13
|
+
"I",
|
|
14
|
+
"KBD",
|
|
15
|
+
"Q",
|
|
16
|
+
"SMALL",
|
|
17
|
+
"STRONG",
|
|
18
|
+
"SUB",
|
|
19
|
+
"SUP",
|
|
20
|
+
"U"
|
|
21
|
+
],
|
|
22
|
+
"v3": [
|
|
23
|
+
"A",
|
|
24
|
+
"BDI",
|
|
25
|
+
"BR",
|
|
26
|
+
"WBR",
|
|
27
|
+
"DEL",
|
|
28
|
+
"DFN",
|
|
29
|
+
"INS",
|
|
30
|
+
"S",
|
|
31
|
+
"SPAN",
|
|
32
|
+
"MARK"
|
|
33
|
+
]
|
|
34
|
+
};
|
|
35
|
+
/** Weglot word types: what a translatable string is attached to. */
|
|
36
|
+
const WORD_TYPE = {
|
|
37
|
+
"OTHER": 0,
|
|
38
|
+
"TEXT": 1,
|
|
39
|
+
"VALUE": 2,
|
|
40
|
+
"PLACEHOLDER": 3,
|
|
41
|
+
"META_CONTENT": 4,
|
|
42
|
+
"IFRAME_SRC": 5,
|
|
43
|
+
"IMG_SRC": 6,
|
|
44
|
+
"IMG_ALT": 7,
|
|
45
|
+
"PDF_HREF": 8,
|
|
46
|
+
"PAGE_TITLE": 9,
|
|
47
|
+
"EXTERNAL_LINK": 10
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { MERGE_NODES, WORD_TYPE };
|
|
52
|
+
//# sourceMappingURL=definitions.generated.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"definitions.generated.mjs","names":["MERGE_NODES: Readonly<Record<string, readonly string[]>>","WORD_TYPE: Readonly<Record<string, number>>"],"sources":["../../../../src/translators/weglot/definitions/definitions.generated.ts"],"sourcesContent":["// Generated by scripts/sync-definitions.ts from weglot/weglot-translation-definitions@79f2a72.\n// Do not edit: run `pnpm sync-definitions` instead.\n\n/** Inline elements merged into the surrounding segment, by engine version. */\nexport const MERGE_NODES: Readonly<Record<string, readonly string[]>> = {\n \"v1\": [],\n \"v2\": [\"ABBR\",\"ACRONYM\",\"B\",\"BDO\",\"BIG\",\"CITE\",\"EM\",\"I\",\"KBD\",\"Q\",\"SMALL\",\"STRONG\",\"SUB\",\"SUP\",\"U\"],\n \"v3\": [\"A\",\"BDI\",\"BR\",\"WBR\",\"DEL\",\"DFN\",\"INS\",\"S\",\"SPAN\",\"MARK\"],\n};\n\n/** Weglot word types: what a translatable string is attached to. */\nexport const WORD_TYPE: Readonly<Record<string, number>> = {\n \"OTHER\": 0,\n \"TEXT\": 1,\n \"VALUE\": 2,\n \"PLACEHOLDER\": 3,\n \"META_CONTENT\": 4,\n \"IFRAME_SRC\": 5,\n \"IMG_SRC\": 6,\n \"IMG_ALT\": 7,\n \"PDF_HREF\": 8,\n \"PAGE_TITLE\": 9,\n \"EXTERNAL_LINK\": 10,\n};\n"],"mappings":";;AAIA,MAAaA,cAA2D;CACtE,MAAM,EAAE;CACR,MAAM;EAAC;EAAO;EAAU;EAAI;EAAM;EAAM;EAAO;EAAK;EAAI;EAAM;EAAI;EAAQ;EAAS;EAAM;EAAM;EAAI;CACnG,MAAM;EAAC;EAAI;EAAM;EAAK;EAAM;EAAM;EAAM;EAAM;EAAI;EAAO;EAAO;CACjE;;AAGD,MAAaC,YAA8C;CACzD,SAAS;CACT,QAAQ;CACR,SAAS;CACT,eAAe;CACf,gBAAgB;CAChB,cAAc;CACd,WAAW;CACX,WAAW;CACX,YAAY;CACZ,cAAc;CACd,iBAAiB;CAClB"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const require_definitions_generated = require('./definitions/definitions.generated.cjs');
|
|
2
|
+
|
|
3
|
+
//#region src/translators/weglot/engine.ts
|
|
4
|
+
/**
|
|
5
|
+
* The engine version and the inline tags it merges: sending a tag it does not
|
|
6
|
+
* merge gets the segment back untranslated, so the set follows the project.
|
|
7
|
+
*/
|
|
8
|
+
/** connect-edge's default for a modern key. weglot-js still defaults to 2. */
|
|
9
|
+
const DEFAULT_MODERN_ENGINE = 3;
|
|
10
|
+
/** Fallback tag for a placeholder or unknown element; the name is only a hint,
|
|
11
|
+
* so the first permitted one wins. */
|
|
12
|
+
const FALLBACK_TAG_PREFERENCE = [
|
|
13
|
+
"span",
|
|
14
|
+
"bdi",
|
|
15
|
+
"u",
|
|
16
|
+
"b"
|
|
17
|
+
];
|
|
18
|
+
function resolveTranslationEngine(fromSettings) {
|
|
19
|
+
if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
|
|
20
|
+
return DEFAULT_MODERN_ENGINE;
|
|
21
|
+
}
|
|
22
|
+
function mergeableTagsFor(engine) {
|
|
23
|
+
const tags = [];
|
|
24
|
+
if (engine >= 2) tags.push(...require_definitions_generated.MERGE_NODES.v2);
|
|
25
|
+
if (engine > 2) tags.push(...require_definitions_generated.MERGE_NODES.v3);
|
|
26
|
+
return new Set(tags.map((tag) => tag.toLowerCase()));
|
|
27
|
+
}
|
|
28
|
+
/** Undefined on engine 1, which merges nothing and so permits no tag at all. */
|
|
29
|
+
function fallbackWireTagFor(tags) {
|
|
30
|
+
return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Every inline tag any engine merges. Fixed rather than per-project: the hash
|
|
34
|
+
* follows the stored text, so a remote setting would re-hash on every change.
|
|
35
|
+
*/
|
|
36
|
+
const INLINE_TAGS = new Set(Object.values(require_definitions_generated.MERGE_NODES).flat().map((tag) => tag.toLowerCase()));
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
exports.DEFAULT_MODERN_ENGINE = DEFAULT_MODERN_ENGINE;
|
|
40
|
+
exports.INLINE_TAGS = INLINE_TAGS;
|
|
41
|
+
exports.fallbackWireTagFor = fallbackWireTagFor;
|
|
42
|
+
exports.mergeableTagsFor = mergeableTagsFor;
|
|
43
|
+
exports.resolveTranslationEngine = resolveTranslationEngine;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { MERGE_NODES } from "./definitions/definitions.generated.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/translators/weglot/engine.ts
|
|
4
|
+
/**
|
|
5
|
+
* The engine version and the inline tags it merges: sending a tag it does not
|
|
6
|
+
* merge gets the segment back untranslated, so the set follows the project.
|
|
7
|
+
*/
|
|
8
|
+
/** connect-edge's default for a modern key. weglot-js still defaults to 2. */
|
|
9
|
+
const DEFAULT_MODERN_ENGINE = 3;
|
|
10
|
+
/** Fallback tag for a placeholder or unknown element; the name is only a hint,
|
|
11
|
+
* so the first permitted one wins. */
|
|
12
|
+
const FALLBACK_TAG_PREFERENCE = [
|
|
13
|
+
"span",
|
|
14
|
+
"bdi",
|
|
15
|
+
"u",
|
|
16
|
+
"b"
|
|
17
|
+
];
|
|
18
|
+
function resolveTranslationEngine(fromSettings) {
|
|
19
|
+
if (typeof fromSettings === "number" && Number.isFinite(fromSettings) && fromSettings > 0) return fromSettings;
|
|
20
|
+
return DEFAULT_MODERN_ENGINE;
|
|
21
|
+
}
|
|
22
|
+
function mergeableTagsFor(engine) {
|
|
23
|
+
const tags = [];
|
|
24
|
+
if (engine >= 2) tags.push(...MERGE_NODES.v2);
|
|
25
|
+
if (engine > 2) tags.push(...MERGE_NODES.v3);
|
|
26
|
+
return new Set(tags.map((tag) => tag.toLowerCase()));
|
|
27
|
+
}
|
|
28
|
+
/** Undefined on engine 1, which merges nothing and so permits no tag at all. */
|
|
29
|
+
function fallbackWireTagFor(tags) {
|
|
30
|
+
return FALLBACK_TAG_PREFERENCE.find((tag) => tags.has(tag));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Every inline tag any engine merges. Fixed rather than per-project: the hash
|
|
34
|
+
* follows the stored text, so a remote setting would re-hash on every change.
|
|
35
|
+
*/
|
|
36
|
+
const INLINE_TAGS = new Set(Object.values(MERGE_NODES).flat().map((tag) => tag.toLowerCase()));
|
|
37
|
+
|
|
38
|
+
//#endregion
|
|
39
|
+
export { DEFAULT_MODERN_ENGINE, INLINE_TAGS, fallbackWireTagFor, mergeableTagsFor, resolveTranslationEngine };
|
|
40
|
+
//# sourceMappingURL=engine.mjs.map
|
|
@@ -0,0 +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/** 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"}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
const require_api_client = require('./api-client.cjs');
|
|
2
|
+
const require_engine = require('./engine.cjs');
|
|
3
|
+
const require_wire_format = require('./wire-format.cjs');
|
|
4
|
+
|
|
5
|
+
//#region src/translators/weglot/translator.ts
|
|
6
|
+
var WeglotTranslator = class {
|
|
7
|
+
client;
|
|
8
|
+
engine;
|
|
9
|
+
constructor(config, logger, client, pollOptions = {}) {
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.logger = logger;
|
|
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);
|
|
15
|
+
}
|
|
16
|
+
async translate(locale, entriesMap) {
|
|
17
|
+
const hashes = Object.keys(entriesMap);
|
|
18
|
+
this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
|
|
19
|
+
const translations = {};
|
|
20
|
+
const protectedEntries = [];
|
|
21
|
+
for (const hash of hashes) {
|
|
22
|
+
const sourceText = entriesMap[hash].text;
|
|
23
|
+
const { wire, restore, encodable } = require_wire_format.encodeForApi(sourceText, this.engine);
|
|
24
|
+
if (!encodable) {
|
|
25
|
+
this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
|
|
26
|
+
translations[hash] = sourceText;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
protectedEntries.push({
|
|
30
|
+
hash,
|
|
31
|
+
text: wire,
|
|
32
|
+
restore
|
|
33
|
+
});
|
|
34
|
+
}
|
|
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.`);
|
|
62
|
+
return translations;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
//#endregion
|
|
67
|
+
exports.WeglotTranslator = WeglotTranslator;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { WeglotApiClient } from "./api-client.mjs";
|
|
2
|
+
import { resolveTranslationEngine } from "./engine.mjs";
|
|
3
|
+
import { encodeForApi } from "./wire-format.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/translators/weglot/translator.ts
|
|
6
|
+
var WeglotTranslator = class {
|
|
7
|
+
client;
|
|
8
|
+
engine;
|
|
9
|
+
constructor(config, logger, client, pollOptions = {}) {
|
|
10
|
+
this.config = config;
|
|
11
|
+
this.logger = logger;
|
|
12
|
+
this.pollOptions = pollOptions;
|
|
13
|
+
this.client = client ?? new WeglotApiClient(config.apiKey, config.apiBaseUrl);
|
|
14
|
+
this.engine = resolveTranslationEngine(config.translationEngine);
|
|
15
|
+
}
|
|
16
|
+
async translate(locale, entriesMap) {
|
|
17
|
+
const hashes = Object.keys(entriesMap);
|
|
18
|
+
this.logger.debug(`Weglot translate() called for ${locale} with ${hashes.length} entries`);
|
|
19
|
+
const translations = {};
|
|
20
|
+
const protectedEntries = [];
|
|
21
|
+
for (const hash of hashes) {
|
|
22
|
+
const sourceText = entriesMap[hash].text;
|
|
23
|
+
const { wire, restore, encodable } = encodeForApi(sourceText, this.engine);
|
|
24
|
+
if (!encodable) {
|
|
25
|
+
this.logger.warn(`Weglot translation engine ${this.engine} cannot carry the markup in hash "${hash}"; falling back to source text.`);
|
|
26
|
+
translations[hash] = sourceText;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
protectedEntries.push({
|
|
30
|
+
hash,
|
|
31
|
+
text: wire,
|
|
32
|
+
restore
|
|
33
|
+
});
|
|
34
|
+
}
|
|
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.`);
|
|
62
|
+
return translations;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
//#endregion
|
|
67
|
+
export { WeglotTranslator };
|
|
68
|
+
//# sourceMappingURL=translator.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
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"}
|