@weglot/translate-react 0.2.2 → 0.3.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 +96 -9
- package/build/plugin/next.cjs +13 -2
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +13 -2
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/transform/index.cjs +17 -3
- package/build/plugin/transform/index.mjs +17 -3
- package/build/plugin/transform/index.mjs.map +1 -1
- package/build/plugin/transform/msg.cjs +66 -0
- package/build/plugin/transform/msg.mjs +64 -0
- package/build/plugin/transform/msg.mjs.map +1 -0
- package/build/plugin/transform/process-file.cjs +9 -7
- package/build/plugin/transform/process-file.mjs +9 -7
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/plugin/transform/utils.cjs +1 -0
- package/build/plugin/transform/utils.mjs +1 -1
- package/build/plugin/transform/utils.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +3 -2
- package/build/plugin/unplugin.d.cts.map +1 -1
- package/build/plugin/unplugin.d.mts.map +1 -1
- package/build/plugin/unplugin.mjs +3 -2
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/react/client/index.cjs +2 -0
- package/build/react/client/index.d.cts +2 -1
- package/build/react/client/index.d.mts +2 -1
- package/build/react/client/index.mjs +2 -1
- package/build/react/client/useTranslation.cjs +14 -2
- package/build/react/client/useTranslation.d.cts +0 -35
- package/build/react/client/useTranslation.d.cts.map +1 -1
- package/build/react/client/useTranslation.d.mts +0 -35
- package/build/react/client/useTranslation.d.mts.map +1 -1
- package/build/react/client/useTranslation.mjs +15 -3
- package/build/react/client/useTranslation.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.mts +2 -2
- package/build/react/server/index.cjs +2 -0
- package/build/react/server/index.d.cts +2 -1
- package/build/react/server/index.d.mts +2 -1
- package/build/react/server/index.mjs +2 -1
- package/build/react/server/useTranslation.cjs +6 -4
- package/build/react/server/useTranslation.d.cts.map +1 -1
- package/build/react/server/useTranslation.d.mts.map +1 -1
- package/build/react/server/useTranslation.mjs +6 -4
- package/build/react/server/useTranslation.mjs.map +1 -1
- package/build/react/server-only/index.cjs +5 -3
- package/build/react/server-only/index.d.cts +2 -3
- package/build/react/server-only/index.d.cts.map +1 -1
- package/build/react/server-only/index.d.mts +2 -3
- package/build/react/server-only/index.d.mts.map +1 -1
- package/build/react/server-only/index.mjs +5 -3
- package/build/react/server-only/index.mjs.map +1 -1
- package/build/react/server-only/translations.cjs +21 -1
- package/build/react/server-only/translations.mjs +22 -2
- package/build/react/server-only/translations.mjs.map +1 -1
- package/build/react/shared/LocaleSwitcher.d.mts +2 -2
- package/build/react/shared/WeglotContext.d.mts +1 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- package/build/react/shared/msg.cjs +50 -0
- package/build/react/shared/msg.d.cts +26 -0
- package/build/react/shared/msg.d.cts.map +1 -0
- package/build/react/shared/msg.d.mts +26 -0
- package/build/react/shared/msg.d.mts.map +1 -0
- package/build/react/shared/msg.mjs +47 -0
- package/build/react/shared/msg.mjs.map +1 -0
- package/build/react/types.d.cts +7 -3
- package/build/react/types.d.cts.map +1 -1
- package/build/react/types.d.mts +7 -3
- package/build/react/types.d.mts.map +1 -1
- package/build/runtime/lru-cache.cjs +38 -0
- package/build/runtime/lru-cache.mjs +38 -0
- package/build/runtime/lru-cache.mjs.map +1 -0
- package/build/runtime/translate-dynamic.cjs +71 -17
- package/build/runtime/translate-dynamic.d.cts +2 -0
- package/build/runtime/translate-dynamic.d.cts.map +1 -1
- package/build/runtime/translate-dynamic.d.mts +2 -0
- package/build/runtime/translate-dynamic.d.mts.map +1 -1
- package/build/runtime/translate-dynamic.mjs +71 -17
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +4 -1
- package/build/translators/weglot/api-client.mjs +4 -1
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_logger = require('../../utils/logger.cjs');
|
|
3
|
+
let intl_messageformat = require("intl-messageformat");
|
|
4
|
+
intl_messageformat = require_rolldown_runtime.__toESM(intl_messageformat);
|
|
5
|
+
|
|
6
|
+
//#region src/react/shared/msg.ts
|
|
7
|
+
/**
|
|
8
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
9
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
10
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
15
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
function msg(text, hash = "", values) {
|
|
19
|
+
return values ? {
|
|
20
|
+
hash,
|
|
21
|
+
text,
|
|
22
|
+
values
|
|
23
|
+
} : {
|
|
24
|
+
hash,
|
|
25
|
+
text
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function isMessageDescriptor(value) {
|
|
29
|
+
return typeof value === "object" && value !== null && typeof value.hash === "string" && typeof value.text === "string";
|
|
30
|
+
}
|
|
31
|
+
function formatMessage(message, params, translations, locale) {
|
|
32
|
+
const text = message.hash && translations[message.hash] || message.text;
|
|
33
|
+
const values = params ? {
|
|
34
|
+
...message.values,
|
|
35
|
+
...params
|
|
36
|
+
} : message.values;
|
|
37
|
+
if (!values) return text;
|
|
38
|
+
try {
|
|
39
|
+
const result = new intl_messageformat.default(text, locale).format(values);
|
|
40
|
+
return Array.isArray(result) ? result.join("") : String(result);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
require_logger.logger.warn(`Error formatting message (${text}): ${error}`);
|
|
43
|
+
return text;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
//#endregion
|
|
48
|
+
exports.formatMessage = formatMessage;
|
|
49
|
+
exports.isMessageDescriptor = isMessageDescriptor;
|
|
50
|
+
exports.msg = msg;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/react/shared/msg.d.ts
|
|
2
|
+
type MessageValues = Record<string, string | number | boolean | Date | null | undefined>;
|
|
3
|
+
/**
|
|
4
|
+
* A string marked for translation outside a component, returned by {@link msg}.
|
|
5
|
+
* Pass it to `t()` from `useTranslation()` to get the translated string.
|
|
6
|
+
*/
|
|
7
|
+
interface MessageDescriptor {
|
|
8
|
+
hash: string;
|
|
9
|
+
text: string;
|
|
10
|
+
values?: MessageValues;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
14
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
15
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
20
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
declare function msg(text: string, hash?: string, values?: MessageValues): MessageDescriptor;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { MessageDescriptor, MessageValues, msg };
|
|
26
|
+
//# sourceMappingURL=msg.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.d.cts","names":[],"sources":["../../../src/react/shared/msg.ts"],"sourcesContent":[],"mappings":";AAIY,KAAA,aAAA,GAAgB,MAEE,CAAA,MAFF,EAAA,MAAM,GAAA,MAAA,GAAA,OAAA,GAEJ,IAFI,GAAA,IAAA,GAAA,SAAA,CAAA;AASlC;AAiBA;;;UAjBiB,iBAAA;;;WAGN;;;;;;;;;;;;;iBAcK,GAAA,uCAGL,gBACR"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//#region src/react/shared/msg.d.ts
|
|
2
|
+
type MessageValues = Record<string, string | number | boolean | Date | null | undefined>;
|
|
3
|
+
/**
|
|
4
|
+
* A string marked for translation outside a component, returned by {@link msg}.
|
|
5
|
+
* Pass it to `t()` from `useTranslation()` to get the translated string.
|
|
6
|
+
*/
|
|
7
|
+
interface MessageDescriptor {
|
|
8
|
+
hash: string;
|
|
9
|
+
text: string;
|
|
10
|
+
values?: MessageValues;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
14
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
15
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
20
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
declare function msg(text: string, hash?: string, values?: MessageValues): MessageDescriptor;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { MessageDescriptor, MessageValues, msg };
|
|
26
|
+
//# sourceMappingURL=msg.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.d.mts","names":[],"sources":["../../../src/react/shared/msg.ts"],"sourcesContent":[],"mappings":";AAIY,KAAA,aAAA,GAAgB,MAEE,CAAA,MAFF,EAAA,MAAM,GAAA,MAAA,GAAA,OAAA,GAEJ,IAFI,GAAA,IAAA,GAAA,SAAA,CAAA;AASlC;AAiBA;;;UAjBiB,iBAAA;;;WAGN;;;;;;;;;;;;;iBAcK,GAAA,uCAGL,gBACR"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { logger } from "../../utils/logger.mjs";
|
|
2
|
+
import IntlMessageFormat from "intl-messageformat";
|
|
3
|
+
|
|
4
|
+
//#region src/react/shared/msg.ts
|
|
5
|
+
/**
|
|
6
|
+
* Marks a string for translation where the compiler cannot see it being
|
|
7
|
+
* rendered, such as a nav array in a data file. The compiler adds the string
|
|
8
|
+
* to the dictionary and fills in `hash` and `values`; never pass them yourself.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import { msg } from "@weglot/translate-react/react";
|
|
13
|
+
* export const NAV = [{ href: "/billing", label: msg("Billing") }];
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
function msg(text, hash = "", values) {
|
|
17
|
+
return values ? {
|
|
18
|
+
hash,
|
|
19
|
+
text,
|
|
20
|
+
values
|
|
21
|
+
} : {
|
|
22
|
+
hash,
|
|
23
|
+
text
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function isMessageDescriptor(value) {
|
|
27
|
+
return typeof value === "object" && value !== null && typeof value.hash === "string" && typeof value.text === "string";
|
|
28
|
+
}
|
|
29
|
+
function formatMessage(message, params, translations, locale) {
|
|
30
|
+
const text = message.hash && translations[message.hash] || message.text;
|
|
31
|
+
const values = params ? {
|
|
32
|
+
...message.values,
|
|
33
|
+
...params
|
|
34
|
+
} : message.values;
|
|
35
|
+
if (!values) return text;
|
|
36
|
+
try {
|
|
37
|
+
const result = new IntlMessageFormat(text, locale).format(values);
|
|
38
|
+
return Array.isArray(result) ? result.join("") : String(result);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
logger.warn(`Error formatting message (${text}): ${error}`);
|
|
41
|
+
return text;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
//#endregion
|
|
46
|
+
export { formatMessage, isMessageDescriptor, msg };
|
|
47
|
+
//# sourceMappingURL=msg.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"msg.mjs","names":[],"sources":["../../../src/react/shared/msg.ts"],"sourcesContent":["import IntlMessageFormat from \"intl-messageformat\";\nimport { logger } from \"../../utils/logger\";\nimport type { LocaleCode } from \"../../locale\";\n\nexport type MessageValues = Record<\n string,\n string | number | boolean | Date | null | undefined\n>;\n\n/**\n * A string marked for translation outside a component, returned by {@link msg}.\n * Pass it to `t()` from `useTranslation()` to get the translated string.\n */\nexport interface MessageDescriptor {\n hash: string;\n text: string;\n values?: MessageValues;\n}\n\n/**\n * Marks a string for translation where the compiler cannot see it being\n * rendered, such as a nav array in a data file. The compiler adds the string\n * to the dictionary and fills in `hash` and `values`; never pass them yourself.\n *\n * @example\n * ```ts\n * import { msg } from \"@weglot/translate-react/react\";\n * export const NAV = [{ href: \"/billing\", label: msg(\"Billing\") }];\n * ```\n */\nexport function msg(\n text: string,\n hash: string = \"\",\n values?: MessageValues,\n): MessageDescriptor {\n return values ? { hash, text, values } : { hash, text };\n}\n\nexport function isMessageDescriptor(\n value: unknown,\n): value is MessageDescriptor {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as MessageDescriptor).hash === \"string\" &&\n typeof (value as MessageDescriptor).text === \"string\"\n );\n}\n\nexport function formatMessage(\n message: MessageDescriptor,\n params: MessageValues | undefined,\n translations: Record<string, string>,\n locale: LocaleCode,\n): string {\n const text = (message.hash && translations[message.hash]) || message.text;\n const values = params ? { ...message.values, ...params } : message.values;\n\n if (!values) {\n return text;\n }\n\n try {\n const result = new IntlMessageFormat(text, locale).format(values);\n return Array.isArray(result) ? result.join(\"\") : String(result);\n } catch (error) {\n logger.warn(`Error formatting message (${text}): ${error}`);\n return text;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAgB,IACd,MACA,OAAe,IACf,QACmB;AACnB,QAAO,SAAS;EAAE;EAAM;EAAM;EAAQ,GAAG;EAAE;EAAM;EAAM;;AAGzD,SAAgB,oBACd,OAC4B;AAC5B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA4B,SAAS,YAC7C,OAAQ,MAA4B,SAAS;;AAIjD,SAAgB,cACd,SACA,QACA,cACA,QACQ;CACR,MAAM,OAAQ,QAAQ,QAAQ,aAAa,QAAQ,SAAU,QAAQ;CACrE,MAAM,SAAS,SAAS;EAAE,GAAG,QAAQ;EAAQ,GAAG;EAAQ,GAAG,QAAQ;AAEnE,KAAI,CAAC,OACH,QAAO;AAGT,KAAI;EACF,MAAM,SAAS,IAAI,kBAAkB,MAAM,OAAO,CAAC,OAAO,OAAO;AACjE,SAAO,MAAM,QAAQ,OAAO,GAAG,OAAO,KAAK,GAAG,GAAG,OAAO,OAAO;UACxD,OAAO;AACd,SAAO,KAAK,6BAA6B,KAAK,KAAK,QAAQ;AAC3D,SAAO"}
|
package/build/react/types.d.cts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { LocaleCode } from "../locale.cjs";
|
|
2
2
|
import { RichTextParams } from "./shared/render-rich-text.cjs";
|
|
3
|
+
import { MessageDescriptor, MessageValues } from "./shared/msg.cjs";
|
|
3
4
|
import { ReactNode } from "react";
|
|
4
5
|
|
|
5
6
|
//#region src/react/types.d.ts
|
|
6
|
-
type TranslationHook = (hashes
|
|
7
|
+
type TranslationHook = (hashes?: string[]) => {
|
|
7
8
|
t: TranslationFunction;
|
|
8
9
|
locale: LocaleCode;
|
|
9
10
|
};
|
|
10
11
|
/**
|
|
11
12
|
* Translation function type
|
|
12
13
|
*/
|
|
13
|
-
|
|
14
|
+
interface TranslationFunction {
|
|
15
|
+
(message: MessageDescriptor, params?: MessageValues): string;
|
|
16
|
+
(hash: string, source: string, params?: RichTextParams): string | ReactNode;
|
|
17
|
+
}
|
|
14
18
|
//#endregion
|
|
15
|
-
export { TranslationHook };
|
|
19
|
+
export { TranslationFunction, TranslationHook };
|
|
16
20
|
//# sourceMappingURL=types.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":";;;;;;KAKY,eAAA;KACP;EADO,MAAA,EAEF,UAFiB;AAQ3B,CAAA;;;;AAEoE,UAFnD,mBAAA,CAEmD;EAAS,CAAA,OAAA,EADjE,iBACiE,EAAA,MAAA,CAAA,EADrC,aACqC,CAAA,EAAA,MAAA;0CAAnC,0BAA0B"}
|
package/build/react/types.d.mts
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
import { LocaleCode } from "../locale.mjs";
|
|
2
2
|
import { RichTextParams } from "./shared/render-rich-text.mjs";
|
|
3
|
+
import { MessageDescriptor, MessageValues } from "./shared/msg.mjs";
|
|
3
4
|
import { ReactNode } from "react";
|
|
4
5
|
|
|
5
6
|
//#region src/react/types.d.ts
|
|
6
|
-
type TranslationHook = (hashes
|
|
7
|
+
type TranslationHook = (hashes?: string[]) => {
|
|
7
8
|
t: TranslationFunction;
|
|
8
9
|
locale: LocaleCode;
|
|
9
10
|
};
|
|
10
11
|
/**
|
|
11
12
|
* Translation function type
|
|
12
13
|
*/
|
|
13
|
-
|
|
14
|
+
interface TranslationFunction {
|
|
15
|
+
(message: MessageDescriptor, params?: MessageValues): string;
|
|
16
|
+
(hash: string, source: string, params?: RichTextParams): string | ReactNode;
|
|
17
|
+
}
|
|
14
18
|
//#endregion
|
|
15
|
-
export { TranslationHook };
|
|
19
|
+
export { TranslationFunction, TranslationHook };
|
|
16
20
|
//# sourceMappingURL=types.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/react/types.ts"],"sourcesContent":[],"mappings":";;;;;;KAKY,eAAA;KACP;EADO,MAAA,EAEF,UAFiB;AAQ3B,CAAA;;;;AAEoE,UAFnD,mBAAA,CAEmD;EAAS,CAAA,OAAA,EADjE,iBACiE,EAAA,MAAA,CAAA,EADrC,aACqC,CAAA,EAAA,MAAA;0CAAnC,0BAA0B"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/runtime/lru-cache.ts
|
|
3
|
+
/** A Map kept in recency order: the first key is the least recently used. */
|
|
4
|
+
var LruCache = class {
|
|
5
|
+
entries = /* @__PURE__ */ new Map();
|
|
6
|
+
constructor(maxSize) {
|
|
7
|
+
this.maxSize = maxSize;
|
|
8
|
+
}
|
|
9
|
+
get size() {
|
|
10
|
+
return this.entries.size;
|
|
11
|
+
}
|
|
12
|
+
get(key) {
|
|
13
|
+
const value = this.entries.get(key);
|
|
14
|
+
if (value === void 0) return void 0;
|
|
15
|
+
this.entries.delete(key);
|
|
16
|
+
this.entries.set(key, value);
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
set(key, value) {
|
|
20
|
+
this.entries.delete(key);
|
|
21
|
+
if (this.maxSize <= 0) return;
|
|
22
|
+
this.entries.set(key, value);
|
|
23
|
+
this.evict();
|
|
24
|
+
}
|
|
25
|
+
resize(maxSize) {
|
|
26
|
+
this.maxSize = maxSize;
|
|
27
|
+
this.evict();
|
|
28
|
+
}
|
|
29
|
+
clear() {
|
|
30
|
+
this.entries.clear();
|
|
31
|
+
}
|
|
32
|
+
evict() {
|
|
33
|
+
while (this.entries.size > Math.max(this.maxSize, 0)) this.entries.delete(this.entries.keys().next().value);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.LruCache = LruCache;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/runtime/lru-cache.ts
|
|
2
|
+
/** A Map kept in recency order: the first key is the least recently used. */
|
|
3
|
+
var LruCache = class {
|
|
4
|
+
entries = /* @__PURE__ */ new Map();
|
|
5
|
+
constructor(maxSize) {
|
|
6
|
+
this.maxSize = maxSize;
|
|
7
|
+
}
|
|
8
|
+
get size() {
|
|
9
|
+
return this.entries.size;
|
|
10
|
+
}
|
|
11
|
+
get(key) {
|
|
12
|
+
const value = this.entries.get(key);
|
|
13
|
+
if (value === void 0) return void 0;
|
|
14
|
+
this.entries.delete(key);
|
|
15
|
+
this.entries.set(key, value);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
set(key, value) {
|
|
19
|
+
this.entries.delete(key);
|
|
20
|
+
if (this.maxSize <= 0) return;
|
|
21
|
+
this.entries.set(key, value);
|
|
22
|
+
this.evict();
|
|
23
|
+
}
|
|
24
|
+
resize(maxSize) {
|
|
25
|
+
this.maxSize = maxSize;
|
|
26
|
+
this.evict();
|
|
27
|
+
}
|
|
28
|
+
clear() {
|
|
29
|
+
this.entries.clear();
|
|
30
|
+
}
|
|
31
|
+
evict() {
|
|
32
|
+
while (this.entries.size > Math.max(this.maxSize, 0)) this.entries.delete(this.entries.keys().next().value);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { LruCache };
|
|
38
|
+
//# sourceMappingURL=lru-cache.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lru-cache.mjs","names":["maxSize: number"],"sources":["../../src/runtime/lru-cache.ts"],"sourcesContent":["/** A Map kept in recency order: the first key is the least recently used. */\nexport class LruCache<V> {\n private readonly entries = new Map<string, V>();\n\n constructor(private maxSize: number) {}\n\n get size(): number {\n return this.entries.size;\n }\n\n get(key: string): V | undefined {\n const value = this.entries.get(key);\n if (value === undefined) return undefined;\n this.entries.delete(key);\n this.entries.set(key, value);\n return value;\n }\n\n set(key: string, value: V): void {\n this.entries.delete(key);\n if (this.maxSize <= 0) return;\n this.entries.set(key, value);\n this.evict();\n }\n\n resize(maxSize: number): void {\n this.maxSize = maxSize;\n this.evict();\n }\n\n clear(): void {\n this.entries.clear();\n }\n\n private evict(): void {\n while (this.entries.size > Math.max(this.maxSize, 0)) {\n this.entries.delete(this.entries.keys().next().value!);\n }\n }\n}\n"],"mappings":";;AACA,IAAa,WAAb,MAAyB;CACvB,AAAiB,0BAAU,IAAI,KAAgB;CAE/C,YAAY,AAAQA,SAAiB;EAAjB;;CAEpB,IAAI,OAAe;AACjB,SAAO,KAAK,QAAQ;;CAGtB,IAAI,KAA4B;EAC9B,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;AACnC,MAAI,UAAU,OAAW,QAAO;AAChC,OAAK,QAAQ,OAAO,IAAI;AACxB,OAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,SAAO;;CAGT,IAAI,KAAa,OAAgB;AAC/B,OAAK,QAAQ,OAAO,IAAI;AACxB,MAAI,KAAK,WAAW,EAAG;AACvB,OAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,OAAK,OAAO;;CAGd,OAAO,SAAuB;AAC5B,OAAK,UAAU;AACf,OAAK,OAAO;;CAGd,QAAc;AACZ,OAAK,QAAQ,OAAO;;CAGtB,AAAQ,QAAc;AACpB,SAAO,KAAK,QAAQ,OAAO,KAAK,IAAI,KAAK,SAAS,EAAE,CAClD,MAAK,QAAQ,OAAO,KAAK,QAAQ,MAAM,CAAC,MAAM,CAAC,MAAO"}
|
|
@@ -4,6 +4,7 @@ const require_timeout = require('../utils/timeout.cjs');
|
|
|
4
4
|
const require_definitions_generated = require('../translators/weglot/definitions/definitions.generated.cjs');
|
|
5
5
|
const require_api_client = require('../translators/weglot/api-client.cjs');
|
|
6
6
|
const require_segmenter = require('./html/segmenter.cjs');
|
|
7
|
+
const require_lru_cache = require('./lru-cache.cjs');
|
|
7
8
|
let react = require("react");
|
|
8
9
|
let _weglot_translate_react_virtual_config = require("@weglot/translate-react/virtual/config");
|
|
9
10
|
let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-react/virtual/locale/server");
|
|
@@ -11,23 +12,37 @@ let _weglot_translate_react_virtual_locale_server = require("@weglot/translate-r
|
|
|
11
12
|
//#region src/runtime/translate-dynamic.ts
|
|
12
13
|
/**
|
|
13
14
|
* Runtime translation for content the compiler cannot see — a CMS title, an API
|
|
14
|
-
* record.
|
|
15
|
+
* record. Translations are kept in memory across requests, so content is only
|
|
16
|
+
* slow on its first view.
|
|
15
17
|
*/
|
|
16
18
|
/** Matches the translate API's own limit, as in the build-time translator. */
|
|
17
19
|
const MAX_WORDS_PER_REQUEST = 100;
|
|
18
20
|
/** Batches are shared across concurrent renders, so a busy server queues many pages. */
|
|
19
21
|
const MAX_CONCURRENT_REQUESTS = 4;
|
|
22
|
+
/** Collection window: server components render concurrently, so this gathers a
|
|
23
|
+
* whole page into one call. */
|
|
24
|
+
const DEFAULT_BATCH_WINDOW_MS = 5;
|
|
25
|
+
/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm
|
|
26
|
+
* call and cuts off a cold one. */
|
|
27
|
+
const DEFAULT_TIMEOUT_MS = 500;
|
|
28
|
+
const DEFAULT_CACHE_SIZE = 1e4;
|
|
29
|
+
/** Seconds a render that served source text stays cached before Next renders it again. */
|
|
30
|
+
const FALLBACK_REVALIDATE_SECONDS = 1;
|
|
20
31
|
let config = {
|
|
21
32
|
apiKey: void 0,
|
|
22
|
-
timeoutMs:
|
|
23
|
-
batchWindowMs:
|
|
33
|
+
timeoutMs: DEFAULT_TIMEOUT_MS,
|
|
34
|
+
batchWindowMs: DEFAULT_BATCH_WINDOW_MS,
|
|
35
|
+
cacheSize: DEFAULT_CACHE_SIZE
|
|
24
36
|
};
|
|
37
|
+
const translations = new require_lru_cache.LruCache(DEFAULT_CACHE_SIZE);
|
|
38
|
+
const cacheKey = (locale, text, type) => `${locale}\u0000${type}\u0000${text}`;
|
|
25
39
|
/** Optional: the key otherwise comes from WEGLOT_API_KEY. */
|
|
26
40
|
function configureDynamicTranslation(next) {
|
|
27
41
|
config = {
|
|
28
42
|
...config,
|
|
29
43
|
...next
|
|
30
44
|
};
|
|
45
|
+
translations.resize(config.cacheSize);
|
|
31
46
|
}
|
|
32
47
|
function resolveApiKey() {
|
|
33
48
|
return config.apiKey ?? process.env.WEGLOT_API_KEY;
|
|
@@ -45,6 +60,23 @@ function memoFor() {
|
|
|
45
60
|
return null;
|
|
46
61
|
}
|
|
47
62
|
}
|
|
63
|
+
/** Cuts the page's revalidation so Next does not keep serving the source text. */
|
|
64
|
+
async function shortenRevalidation() {
|
|
65
|
+
try {
|
|
66
|
+
const { unstable_cache } = await import("next/cache");
|
|
67
|
+
await unstable_cache(async () => null, ["weglot-dynamic-fallback"], { revalidate: FALLBACK_REVALIDATE_SECONDS })();
|
|
68
|
+
} catch (error) {
|
|
69
|
+
require_logger.logger.debug(`Could not shorten the revalidation of a page with untranslated dynamic content: ${error instanceof Error ? error.message : String(error)}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function translateWord(locale, text, timeoutMs, type = require_definitions_generated.WORD_TYPE.TEXT) {
|
|
73
|
+
const cached = translations.get(cacheKey(locale, text, type));
|
|
74
|
+
if (cached !== void 0) return Promise.resolve({
|
|
75
|
+
text: cached,
|
|
76
|
+
fallback: false
|
|
77
|
+
});
|
|
78
|
+
return enqueue(locale, text, timeoutMs, type);
|
|
79
|
+
}
|
|
48
80
|
function enqueue(locale, text, timeoutMs, type) {
|
|
49
81
|
const key = batchKey(locale, timeoutMs);
|
|
50
82
|
return new Promise((resolve) => {
|
|
@@ -66,7 +98,10 @@ async function flush(key, locale, timeoutMs) {
|
|
|
66
98
|
const apiKey = resolveApiKey();
|
|
67
99
|
if (!apiKey) {
|
|
68
100
|
require_logger.logger.warn("Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).");
|
|
69
|
-
queue.forEach((word) => word.resolve(
|
|
101
|
+
queue.forEach((word) => word.resolve({
|
|
102
|
+
text: word.text,
|
|
103
|
+
fallback: false
|
|
104
|
+
}));
|
|
70
105
|
return;
|
|
71
106
|
}
|
|
72
107
|
const client = new require_api_client.WeglotApiClient(apiKey, _weglot_translate_react_virtual_config.apiBaseUrl);
|
|
@@ -74,30 +109,45 @@ async function flush(key, locale, timeoutMs) {
|
|
|
74
109
|
for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
|
|
75
110
|
const deadline = Date.now() + timeoutMs;
|
|
76
111
|
let next = 0;
|
|
112
|
+
const fallBack = (chunk) => chunk.forEach((word) => word.resolve({
|
|
113
|
+
text: word.text,
|
|
114
|
+
fallback: true
|
|
115
|
+
}));
|
|
77
116
|
const worker = async () => {
|
|
78
117
|
while (next < chunks.length) {
|
|
79
118
|
const chunk = chunks[next++];
|
|
80
119
|
if (Date.now() >= deadline) {
|
|
81
|
-
chunk
|
|
120
|
+
fallBack(chunk);
|
|
82
121
|
continue;
|
|
83
122
|
}
|
|
123
|
+
const request = client.translate({
|
|
124
|
+
from: _weglot_translate_react_virtual_config.sourceLocale,
|
|
125
|
+
to: _weglot_translate_react_virtual_config.apiLocales[locale] ?? locale,
|
|
126
|
+
words: chunk.map((word) => word.text),
|
|
127
|
+
types: chunk.map((word) => word.type),
|
|
128
|
+
live: true
|
|
129
|
+
});
|
|
130
|
+
request.then(({ words }) => chunk.forEach((word, index) => {
|
|
131
|
+
const result = words[index];
|
|
132
|
+
if (result != null) translations.set(cacheKey(locale, word.text, word.type), result);
|
|
133
|
+
})).catch(() => {});
|
|
84
134
|
try {
|
|
85
|
-
const { words: translated } = await require_timeout.withTimeout(
|
|
86
|
-
from: _weglot_translate_react_virtual_config.sourceLocale,
|
|
87
|
-
to: _weglot_translate_react_virtual_config.apiLocales[locale] ?? locale,
|
|
88
|
-
words: chunk.map((word) => word.text),
|
|
89
|
-
types: chunk.map((word) => word.type ?? require_definitions_generated.WORD_TYPE.TEXT),
|
|
90
|
-
live: true
|
|
91
|
-
}), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
|
|
135
|
+
const { words: translated } = await require_timeout.withTimeout(request, deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
|
|
92
136
|
chunk.forEach((word, index) => {
|
|
93
137
|
const result = translated[index];
|
|
94
138
|
if (result === null) require_logger.logger.debug(`Weglot is still translating dynamic content for locale "${locale}".`);
|
|
95
139
|
else if (result === word.text) require_logger.logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
|
|
96
|
-
word.resolve(result
|
|
140
|
+
word.resolve(result === null ? {
|
|
141
|
+
text: word.text,
|
|
142
|
+
fallback: true
|
|
143
|
+
} : {
|
|
144
|
+
text: result,
|
|
145
|
+
fallback: false
|
|
146
|
+
});
|
|
97
147
|
});
|
|
98
148
|
} catch (error) {
|
|
99
149
|
require_logger.logger.warn(`Dynamic translation to "${locale}" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`);
|
|
100
|
-
chunk
|
|
150
|
+
fallBack(chunk);
|
|
101
151
|
}
|
|
102
152
|
}
|
|
103
153
|
};
|
|
@@ -113,7 +163,10 @@ async function tDynamic(text, options = {}) {
|
|
|
113
163
|
const key = `${batchKey(locale, timeoutMs)}\u0000${text}`;
|
|
114
164
|
const existing = memo?.get(key);
|
|
115
165
|
if (existing) return existing;
|
|
116
|
-
const pending =
|
|
166
|
+
const pending = translateWord(locale, text, timeoutMs).then(async (result) => {
|
|
167
|
+
if (result.fallback) await shortenRevalidation();
|
|
168
|
+
return result.text;
|
|
169
|
+
});
|
|
117
170
|
memo?.set(key, pending);
|
|
118
171
|
return pending;
|
|
119
172
|
}
|
|
@@ -129,8 +182,9 @@ async function tDynamicHtml(html, options = {}) {
|
|
|
129
182
|
const segmenter = new require_segmenter.HtmlSegmenter(html, _weglot_translate_react_virtual_config.translationEngine);
|
|
130
183
|
const segments = segmenter.extract();
|
|
131
184
|
if (segments.length === 0) return html;
|
|
132
|
-
const translated = await Promise.all(segments.map((segment) =>
|
|
133
|
-
|
|
185
|
+
const translated = await Promise.all(segments.map((segment) => translateWord(locale, segment.w, timeoutMs, segment.t)));
|
|
186
|
+
if (translated.some((result) => result.fallback)) await shortenRevalidation();
|
|
187
|
+
return segmenter.apply(translated.map((result) => result.text));
|
|
134
188
|
}
|
|
135
189
|
/** Translates several strings in one pass, sharing a single request. */
|
|
136
190
|
async function tDynamicAll(texts, options = {}) {
|
|
@@ -12,6 +12,8 @@ interface DynamicTranslationConfig {
|
|
|
12
12
|
apiKey?: string;
|
|
13
13
|
timeoutMs?: number;
|
|
14
14
|
batchWindowMs?: number;
|
|
15
|
+
/** Translations kept in memory across requests. 0 disables the cache. */
|
|
16
|
+
cacheSize?: number;
|
|
15
17
|
}
|
|
16
18
|
/** Optional: the key otherwise comes from WEGLOT_API_KEY. */
|
|
17
19
|
declare function configureDynamicTranslation(next: DynamicTranslationConfig): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AAiRsB,UAvOL,yBAAA,CAyON;EA2BW;EA0BA,MAAA,CAAA,EA5RX,UA4RsB;;;;UAvRhB,wBAAA;;;;;;;;iBAwBD,2BAAA,OACR;;iBAuMc,QAAA,yBAEX,4BACR;;;;;iBA0BmB,YAAA,yBAEX,4BACR;;iBAuBmB,WAAA,4BAEX,4BACR"}
|
|
@@ -12,6 +12,8 @@ interface DynamicTranslationConfig {
|
|
|
12
12
|
apiKey?: string;
|
|
13
13
|
timeoutMs?: number;
|
|
14
14
|
batchWindowMs?: number;
|
|
15
|
+
/** Translations kept in memory across requests. 0 disables the cache. */
|
|
16
|
+
cacheSize?: number;
|
|
15
17
|
}
|
|
16
18
|
/** Optional: the key otherwise comes from WEGLOT_API_KEY. */
|
|
17
19
|
declare function configureDynamicTranslation(next: DynamicTranslationConfig): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AAiRsB,UAvOL,yBAAA,CAyON;EA2BW;EA0BA,MAAA,CAAA,EA5RX,UA4RsB;;;;UAvRhB,wBAAA;;;;;;;;iBAwBD,2BAAA,OACR;;iBAuMc,QAAA,yBAEX,4BACR;;;;;iBA0BmB,YAAA,yBAEX,4BACR;;iBAuBmB,WAAA,4BAEX,4BACR"}
|