@weglot/translate-react 0.0.0-stage → 0.1.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 +190 -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 +207 -0
- package/build/plugin/build-translator.mjs +205 -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 +226 -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 +228 -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 +142 -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 +139 -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 +137 -0
- package/build/translators/translation-service.mjs +138 -0
- package/build/translators/translation-service.mjs.map +1 -0
- package/build/translators/weglot/api-client.cjs +79 -0
- package/build/translators/weglot/api-client.mjs +79 -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 +46 -0
- package/build/translators/weglot/engine.mjs +43 -0
- package/build/translators/weglot/engine.mjs.map +1 -0
- package/build/translators/weglot/translator.cjs +61 -0
- package/build/translators/weglot/translator.mjs +62 -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 +143 -0
- package/build/types.d.cts.map +1 -0
- package/build/types.d.mts +143 -0
- package/build/types.d.mts.map +1 -0
- package/build/utils/config-factory.cjs +86 -0
- package/build/utils/config-factory.mjs +83 -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 +56 -0
- package/build/virtual/code-generator.mjs +55 -0
- package/build/virtual/code-generator.mjs.map +1 -0
- package/build/virtual/config.cjs +16 -0
- package/build/virtual/config.d.cts +13 -0
- package/build/virtual/config.d.cts.map +1 -0
- package/build/virtual/config.d.mts +13 -0
- package/build/virtual/config.d.mts.map +1 -0
- package/build/virtual/config.mjs +12 -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,114 @@
|
|
|
1
|
+
import { logger } from "../utils/logger.mjs";
|
|
2
|
+
import { getWeglotDir } from "../utils/path-helpers.mjs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import fs from "fs";
|
|
5
|
+
|
|
6
|
+
//#region src/metadata/manager.ts
|
|
7
|
+
const METADATA_DIR_DEV = "metadata-dev";
|
|
8
|
+
const METADATA_DIR_BUILD = "metadata-build";
|
|
9
|
+
/**
|
|
10
|
+
* Opens an LMDB environment once per path and process: an open() racing another
|
|
11
|
+
* worker's close() double-frees the env (SIGABRT), killing Turbopack's worker.
|
|
12
|
+
*
|
|
13
|
+
* lmdb is loaded via dynamic import() to prevent bundlers and require hooks
|
|
14
|
+
* from transforming its CJS bundle, which contains syntax they can't handle.
|
|
15
|
+
*/
|
|
16
|
+
const connections = /* @__PURE__ */ new Map();
|
|
17
|
+
function openDatabaseConnection(dbPath, noSync) {
|
|
18
|
+
const existing = connections.get(dbPath);
|
|
19
|
+
if (existing) return existing;
|
|
20
|
+
const opening = (async () => {
|
|
21
|
+
try {
|
|
22
|
+
fs.mkdirSync(dbPath, { recursive: true });
|
|
23
|
+
const { open } = await import("lmdb");
|
|
24
|
+
return open({
|
|
25
|
+
path: dbPath,
|
|
26
|
+
compression: true,
|
|
27
|
+
noSync
|
|
28
|
+
});
|
|
29
|
+
} catch (error) {
|
|
30
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
31
|
+
throw new Error(`Failed to open LMDB at ${dbPath}: ${message}`);
|
|
32
|
+
}
|
|
33
|
+
})();
|
|
34
|
+
connections.set(dbPath, opening);
|
|
35
|
+
opening.catch(() => connections.delete(dbPath));
|
|
36
|
+
return opening;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Closes the cached connection. Also prevents EBUSY/EPERM on Windows during
|
|
40
|
+
* directory cleanup.
|
|
41
|
+
*/
|
|
42
|
+
async function closeMetadataDatabase(dbPath) {
|
|
43
|
+
const opening = connections.get(dbPath);
|
|
44
|
+
if (!opening) return;
|
|
45
|
+
connections.delete(dbPath);
|
|
46
|
+
try {
|
|
47
|
+
await (await opening).close();
|
|
48
|
+
} catch (e) {
|
|
49
|
+
logger.debug(`Error closing database at ${dbPath}: ${e}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Runs the callback against the connection for this path. The connection is
|
|
54
|
+
* left open for the life of the process; see openDatabaseConnection.
|
|
55
|
+
*/
|
|
56
|
+
async function runWithDbConnection(dbPath, noSync, fn) {
|
|
57
|
+
return fn(await openDatabaseConnection(dbPath, noSync));
|
|
58
|
+
}
|
|
59
|
+
function readEntriesFromDb(db) {
|
|
60
|
+
const entries = {};
|
|
61
|
+
for (const { key, value } of db.getRange()) entries[key] = value;
|
|
62
|
+
return entries;
|
|
63
|
+
}
|
|
64
|
+
async function loadMetadata(dbPath, noSync = false) {
|
|
65
|
+
return runWithDbConnection(dbPath, noSync, readEntriesFromDb);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Persists translation entries to LMDB in a single atomic transaction.
|
|
69
|
+
*/
|
|
70
|
+
async function saveMetadata(dbPath, entries, noSync = false) {
|
|
71
|
+
return runWithDbConnection(dbPath, noSync, (db) => {
|
|
72
|
+
db.transactionSync(() => {
|
|
73
|
+
for (const entry of entries) db.putSync(entry.hash, entry);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
function cleanupExistingMetadata(metadataDbPath) {
|
|
78
|
+
logger.debug(`Cleaning up metadata database: ${metadataDbPath}`);
|
|
79
|
+
closeMetadataDatabase(metadataDbPath);
|
|
80
|
+
try {
|
|
81
|
+
fs.rmSync(metadataDbPath, {
|
|
82
|
+
recursive: true,
|
|
83
|
+
force: true
|
|
84
|
+
});
|
|
85
|
+
logger.info(`🧹 Cleaned up metadata database: ${metadataDbPath}`);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
const code = error instanceof Error && "code" in error ? error.code : void 0;
|
|
88
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
89
|
+
if (code === "ENOENT") {
|
|
90
|
+
logger.debug(`Metadata database already deleted or doesn't exist: ${metadataDbPath}`);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
logger.warn(`Failed to cleanup metadata database: ${message}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Cleared between builds so a stale entry is not paid for, but kept in development
|
|
98
|
+
* where clearing leaves cache-served hashes unresolvable.
|
|
99
|
+
*/
|
|
100
|
+
function cleanupMetadataForEnvironment(metadataDbPath, environment) {
|
|
101
|
+
if (environment === "development") {
|
|
102
|
+
logger.debug(`Keeping development metadata database: ${metadataDbPath}`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
cleanupExistingMetadata(metadataDbPath);
|
|
106
|
+
}
|
|
107
|
+
function getMetadataPath(config) {
|
|
108
|
+
const dirname = config.environment === "development" ? METADATA_DIR_DEV : METADATA_DIR_BUILD;
|
|
109
|
+
return path.join(getWeglotDir(config), dirname);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
//#endregion
|
|
113
|
+
export { cleanupMetadataForEnvironment, getMetadataPath, loadMetadata, saveMetadata };
|
|
114
|
+
//# sourceMappingURL=manager.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manager.mjs","names":["entries: MetadataSchema"],"sources":["../../src/metadata/manager.ts"],"sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport type { RootDatabase } from \"lmdb\";\nimport type { MetadataSchema, PathConfig, TranslationEntry } from \"../types\";\nimport { getWeglotDir } from \"../utils/path-helpers\";\nimport { logger } from \"../utils/logger\";\n\nconst METADATA_DIR_DEV = \"metadata-dev\";\nconst METADATA_DIR_BUILD = \"metadata-build\";\n\n/**\n * Opens an LMDB environment once per path and process: an open() racing another\n * worker's close() double-frees the env (SIGABRT), killing Turbopack's worker.\n *\n * lmdb is loaded via dynamic import() to prevent bundlers and require hooks\n * from transforming its CJS bundle, which contains syntax they can't handle.\n */\nconst connections = new Map<string, Promise<RootDatabase>>();\n\nfunction openDatabaseConnection(\n dbPath: string,\n noSync: boolean,\n): Promise<RootDatabase> {\n const existing = connections.get(dbPath);\n if (existing) return existing;\n\n const opening = (async () => {\n try {\n fs.mkdirSync(dbPath, { recursive: true });\n const { open } = await import(\"lmdb\");\n return open({\n path: dbPath,\n compression: true,\n noSync,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to open LMDB at ${dbPath}: ${message}`);\n }\n })();\n\n connections.set(dbPath, opening);\n // A failed open must not be cached, or every later operation replays it.\n opening.catch(() => connections.delete(dbPath));\n return opening;\n}\n\n/**\n * Closes the cached connection. Also prevents EBUSY/EPERM on Windows during\n * directory cleanup.\n */\nexport async function closeMetadataDatabase(dbPath: string): Promise<void> {\n const opening = connections.get(dbPath);\n if (!opening) return;\n connections.delete(dbPath);\n\n try {\n const db = await opening;\n await db.close();\n } catch (e) {\n logger.debug(`Error closing database at ${dbPath}: ${e}`);\n }\n}\n\n/**\n * Runs the callback against the connection for this path. The connection is\n * left open for the life of the process; see openDatabaseConnection.\n */\nasync function runWithDbConnection<T>(\n dbPath: string,\n noSync: boolean,\n fn: (db: RootDatabase) => T,\n): Promise<T> {\n const db = await openDatabaseConnection(dbPath, noSync);\n return fn(db);\n}\n\nfunction readEntriesFromDb(db: RootDatabase): MetadataSchema {\n const entries: MetadataSchema = {};\n\n for (const { key, value } of db.getRange()) {\n entries[key as string] = value as TranslationEntry;\n }\n\n return entries;\n}\n\nexport async function loadMetadata(\n dbPath: string,\n noSync = false,\n): Promise<MetadataSchema> {\n return runWithDbConnection(dbPath, noSync, readEntriesFromDb);\n}\n\n/**\n * Persists translation entries to LMDB in a single atomic transaction.\n */\nexport async function saveMetadata(\n dbPath: string,\n entries: TranslationEntry[],\n noSync = false,\n): Promise<void> {\n return runWithDbConnection(dbPath, noSync, (db) => {\n db.transactionSync(() => {\n for (const entry of entries) {\n db.putSync(entry.hash, entry);\n }\n });\n });\n}\n\nexport function cleanupExistingMetadata(metadataDbPath: string): void {\n logger.debug(`Cleaning up metadata database: ${metadataDbPath}`);\n void closeMetadataDatabase(metadataDbPath);\n\n try {\n fs.rmSync(metadataDbPath, { recursive: true, force: true });\n logger.info(`🧹 Cleaned up metadata database: ${metadataDbPath}`);\n } catch (error) {\n const code =\n error instanceof Error && \"code\" in error\n ? (error as NodeJS.ErrnoException).code\n : undefined;\n const message = error instanceof Error ? error.message : String(error);\n\n if (code === \"ENOENT\") {\n logger.debug(\n `Metadata database already deleted or doesn't exist: ${metadataDbPath}`,\n );\n return;\n }\n\n logger.warn(`Failed to cleanup metadata database: ${message}`);\n }\n}\n\n/**\n * Cleared between builds so a stale entry is not paid for, but kept in development\n * where clearing leaves cache-served hashes unresolvable.\n */\nexport function cleanupMetadataForEnvironment(\n metadataDbPath: string,\n environment: PathConfig[\"environment\"],\n): void {\n if (environment === \"development\") {\n logger.debug(`Keeping development metadata database: ${metadataDbPath}`);\n return;\n }\n cleanupExistingMetadata(metadataDbPath);\n}\n\nexport function getMetadataPath(config: PathConfig): string {\n const dirname =\n config.environment === \"development\"\n ? METADATA_DIR_DEV\n : METADATA_DIR_BUILD;\n return path.join(getWeglotDir(config), dirname);\n}\n"],"mappings":";;;;;;AAOA,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;;;;;;;;AAS3B,MAAM,8BAAc,IAAI,KAAoC;AAE5D,SAAS,uBACP,QACA,QACuB;CACvB,MAAM,WAAW,YAAY,IAAI,OAAO;AACxC,KAAI,SAAU,QAAO;CAErB,MAAM,WAAW,YAAY;AAC3B,MAAI;AACF,MAAG,UAAU,QAAQ,EAAE,WAAW,MAAM,CAAC;GACzC,MAAM,EAAE,SAAS,MAAM,OAAO;AAC9B,UA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MAAgC,OACjC;EACN,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AAEtE,MAAI,SAAS,UAAU;AACrB,UAAO,MACL,uDAAuD,iBACxD;AACD;;AAGF,SAAO,KAAK,wCAAwC,UAAU;;;;;;;AAQlE,SAAgB,8BACd,gBACA,aACM;AACN,KAAI,gBAAgB,eAAe;AACjC,SAAO,MAAM,0CAA0C,iBAAiB;AACxE;;AAEF,yBAAwB,eAAe;;AAGzC,SAAgB,gBAAgB,QAA4B;CAC1D,MAAM,UACJ,OAAO,gBAAgB,gBACnB,mBACA;AACN,QAAO,KAAK,KAAK,aAAa,OAAO,EAAE,QAAQ"}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_logger = require('../utils/logger.cjs');
|
|
3
|
+
const require_api = require('../translators/api.cjs');
|
|
4
|
+
const require_cache_factory = require('../translators/cache-factory.cjs');
|
|
5
|
+
const require_translation_service = require('../translators/translation-service.cjs');
|
|
6
|
+
const require_manager = require('../metadata/manager.cjs');
|
|
7
|
+
const require_translation_server = require('../translation-server/translation-server.cjs');
|
|
8
|
+
let fs_promises = require("fs/promises");
|
|
9
|
+
fs_promises = require_rolldown_runtime.__toESM(fs_promises);
|
|
10
|
+
let path = require("path");
|
|
11
|
+
path = require_rolldown_runtime.__toESM(path);
|
|
12
|
+
|
|
13
|
+
//#region src/plugin/build-translator.ts
|
|
14
|
+
/**
|
|
15
|
+
* Build-time translation processor
|
|
16
|
+
*
|
|
17
|
+
* Handles translation generation and validation at build time
|
|
18
|
+
* Supports two modes:
|
|
19
|
+
* - "translate": Generate all translations, fail if translation fails
|
|
20
|
+
* - "cache-only": Validate cache completeness, fail if incomplete
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Process translations at build time
|
|
24
|
+
*
|
|
25
|
+
* @throws Error if validation or translation fails (causes build to fail)
|
|
26
|
+
*/
|
|
27
|
+
async function processBuildTranslations(options) {
|
|
28
|
+
const { config, publicOutputPath, metadataFilePath } = options;
|
|
29
|
+
const buildMode = process.env.WEGLOT_BUILD_MODE || config.buildMode;
|
|
30
|
+
require_logger.logger.info(`🌍 Build mode: ${buildMode}`);
|
|
31
|
+
const metadata = await require_manager.loadMetadata(metadataFilePath, true);
|
|
32
|
+
if (!metadata || Object.keys(metadata).length === 0) {
|
|
33
|
+
require_logger.logger.info("No translations to process (metadata is empty)");
|
|
34
|
+
return {
|
|
35
|
+
success: true,
|
|
36
|
+
stats: {}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const totalEntries = Object.keys(metadata).length;
|
|
40
|
+
require_logger.logger.info(`📊 Found ${totalEntries} translatable entries`);
|
|
41
|
+
const cache = require_cache_factory.createCache(config);
|
|
42
|
+
if (buildMode === "cache-only") {
|
|
43
|
+
require_logger.logger.info("🔍 Validating translation cache...");
|
|
44
|
+
await validateCache(config, metadata, cache);
|
|
45
|
+
require_logger.logger.info("✅ Cache validation passed");
|
|
46
|
+
if (publicOutputPath) await copyStaticFiles(config, publicOutputPath, metadata, cache);
|
|
47
|
+
return {
|
|
48
|
+
success: true,
|
|
49
|
+
stats: buildCacheStats(config, metadata)
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
require_logger.logger.info("🔄 Generating translations...");
|
|
53
|
+
let translationServer;
|
|
54
|
+
try {
|
|
55
|
+
translationServer = await require_translation_server.startTranslationServer({
|
|
56
|
+
translationService: new require_translation_service.TranslationService(config, require_logger.logger),
|
|
57
|
+
onError: (err) => {
|
|
58
|
+
require_logger.logger.error("Translation server error:", err);
|
|
59
|
+
},
|
|
60
|
+
config
|
|
61
|
+
});
|
|
62
|
+
const allLocales = config.targetLocales;
|
|
63
|
+
require_logger.logger.info(`Processing translations for ${allLocales.length} locale(s)...`);
|
|
64
|
+
const stats = {};
|
|
65
|
+
const errors = [];
|
|
66
|
+
const skipped = [];
|
|
67
|
+
const localePromises = allLocales.map(async (locale) => {
|
|
68
|
+
require_logger.logger.info(`Translating to ${locale}...`);
|
|
69
|
+
const result = await translationServer.translateAll(locale);
|
|
70
|
+
stats[locale] = {
|
|
71
|
+
total: totalEntries,
|
|
72
|
+
translated: Object.keys(result.translations).length,
|
|
73
|
+
failed: result.stats.failed
|
|
74
|
+
};
|
|
75
|
+
if (result.unsupportedLocale) {
|
|
76
|
+
skipped.push(locale);
|
|
77
|
+
if (!await cache.has(locale)) await cache.set(locale, {});
|
|
78
|
+
require_logger.logger.warn(`⏭️ Skipped ${locale}: the Weglot API does not translate ${config.sourceLocale} to ${locale}. Remove the language from the project or ask Weglot support to enable the pair.`);
|
|
79
|
+
} else if (result.errors.length > 0) {
|
|
80
|
+
require_logger.logger.warn(`⚠️ ${result.errors.length} translation error(s) for ${locale}`);
|
|
81
|
+
errors.push({
|
|
82
|
+
locale,
|
|
83
|
+
error: `${result.errors.length} translation(s) failed`
|
|
84
|
+
});
|
|
85
|
+
} else require_logger.logger.info(`✅ ${locale} completed successfully`);
|
|
86
|
+
});
|
|
87
|
+
await Promise.all(localePromises);
|
|
88
|
+
if (errors.length > 0) {
|
|
89
|
+
const errorMsg = formatTranslationErrors(errors);
|
|
90
|
+
require_logger.logger.error(errorMsg);
|
|
91
|
+
process.exit(1);
|
|
92
|
+
}
|
|
93
|
+
if (publicOutputPath) await copyStaticFiles(config, publicOutputPath, metadata, cache);
|
|
94
|
+
if (skipped.length > 0) require_logger.logger.warn(`✅ Translation generation completed, without ${skipped.join(", ")}`);
|
|
95
|
+
else require_logger.logger.info("✅ Translation generation completed successfully");
|
|
96
|
+
return {
|
|
97
|
+
success: true,
|
|
98
|
+
stats
|
|
99
|
+
};
|
|
100
|
+
} catch (error) {
|
|
101
|
+
require_logger.logger.error("❌ Translation generation failed:\n", error instanceof Error ? error.message : error);
|
|
102
|
+
process.exit(1);
|
|
103
|
+
} finally {
|
|
104
|
+
if (translationServer) {
|
|
105
|
+
await translationServer.stop();
|
|
106
|
+
require_logger.logger.info("✅ Translation server stopped");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Validate that all required translations exist in cache
|
|
112
|
+
* @throws Error if cache is incomplete or missing
|
|
113
|
+
*/
|
|
114
|
+
async function validateCache(config, metadata, cache) {
|
|
115
|
+
const allHashes = Object.keys(metadata);
|
|
116
|
+
const missingLocales = [];
|
|
117
|
+
const incompleteLocales = [];
|
|
118
|
+
const allLocales = config.targetLocales;
|
|
119
|
+
for (const locale of allLocales) try {
|
|
120
|
+
const entries = await cache.get(locale);
|
|
121
|
+
if (Object.keys(entries).length === 0) {
|
|
122
|
+
if (await cache.has(locale)) {
|
|
123
|
+
require_logger.logger.warn(`⏭️ ${locale} holds no translations and is served untranslated`);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
missingLocales.push(locale);
|
|
127
|
+
require_logger.logger.debug(`Cache file not found for ${locale}`);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const missingHashes = allHashes.filter((hash) => !entries[hash]);
|
|
131
|
+
if (missingHashes.length > 0) {
|
|
132
|
+
incompleteLocales.push({
|
|
133
|
+
locale,
|
|
134
|
+
missing: missingHashes.length,
|
|
135
|
+
total: allHashes.length
|
|
136
|
+
});
|
|
137
|
+
require_logger.logger.debug(`Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(", ")}${missingHashes.length > 5 ? "..." : ""}`);
|
|
138
|
+
}
|
|
139
|
+
} catch (error) {
|
|
140
|
+
missingLocales.push(locale);
|
|
141
|
+
require_logger.logger.debug(`Failed to read cache for ${locale}:`, error);
|
|
142
|
+
}
|
|
143
|
+
if (missingLocales.length > 0 || incompleteLocales.length > 0) {
|
|
144
|
+
const errorMsg = formatCacheValidationError(missingLocales, incompleteLocales);
|
|
145
|
+
require_logger.logger.error(errorMsg);
|
|
146
|
+
process.exit(1);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function buildCacheStats(config, metadata) {
|
|
150
|
+
const totalEntries = Object.keys(metadata).length;
|
|
151
|
+
const stats = {};
|
|
152
|
+
const allLocales = config.targetLocales;
|
|
153
|
+
for (const locale of allLocales) stats[locale] = {
|
|
154
|
+
total: totalEntries,
|
|
155
|
+
translated: totalEntries,
|
|
156
|
+
failed: 0
|
|
157
|
+
};
|
|
158
|
+
return stats;
|
|
159
|
+
}
|
|
160
|
+
async function copyStaticFiles(config, publicOutputPath, metadata, cache) {
|
|
161
|
+
require_logger.logger.info(`📦 Generating static translation files in ${publicOutputPath}`);
|
|
162
|
+
await fs_promises.default.mkdir(publicOutputPath, { recursive: true });
|
|
163
|
+
const usedHashes = new Set(Object.keys(metadata));
|
|
164
|
+
require_logger.logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);
|
|
165
|
+
const allLocales = config.targetLocales;
|
|
166
|
+
for (const locale of allLocales) {
|
|
167
|
+
const publicFilePath = path.default.join(publicOutputPath, `${locale}.json`);
|
|
168
|
+
try {
|
|
169
|
+
const entries = await cache.get(locale, Array.from(usedHashes));
|
|
170
|
+
const outputData = require_api.dictionaryFrom(locale, entries);
|
|
171
|
+
await fs_promises.default.writeFile(publicFilePath, JSON.stringify(outputData, null, 2), "utf-8");
|
|
172
|
+
require_logger.logger.info(`✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
require_logger.logger.error(`❌ Failed to generate ${locale}.json:`, error);
|
|
175
|
+
process.exit(1);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function formatCacheValidationError(missingLocales, incompleteLocales) {
|
|
180
|
+
let msg = "❌ Cache validation failed in cache-only mode:\n\n";
|
|
181
|
+
if (missingLocales.length > 0) {
|
|
182
|
+
msg += ` 📁 Missing cache files:\n`;
|
|
183
|
+
msg += missingLocales.map((locale) => ` - ${locale}.json`).join("\n");
|
|
184
|
+
msg += "\n\n";
|
|
185
|
+
}
|
|
186
|
+
if (incompleteLocales.length > 0) {
|
|
187
|
+
msg += ` 📊 Incomplete cache:\n`;
|
|
188
|
+
msg += incompleteLocales.map((item) => ` - ${item.locale}: ${item.missing}/${item.total} translations missing`).join("\n");
|
|
189
|
+
msg += "\n\n";
|
|
190
|
+
}
|
|
191
|
+
msg += ` 💡 To fix:\n`;
|
|
192
|
+
msg += ` 1. Set WEGLOT_BUILD_MODE=translate to generate translations\n`;
|
|
193
|
+
msg += ` 2. Commit the generated weglot/cache/*.json files\n`;
|
|
194
|
+
msg += ` 3. Ensure translation API keys are available if generating translations`;
|
|
195
|
+
return msg;
|
|
196
|
+
}
|
|
197
|
+
function formatTranslationErrors(errors) {
|
|
198
|
+
let msg = "❌ Translation generation failed:\n\n";
|
|
199
|
+
msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join("\n");
|
|
200
|
+
msg += "\n\n";
|
|
201
|
+
msg += ` 💡 Translation errors must be resolved in "translate" mode.\n`;
|
|
202
|
+
msg += ` Check translation server logs for details.`;
|
|
203
|
+
return msg;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
//#endregion
|
|
207
|
+
exports.processBuildTranslations = processBuildTranslations;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { logger } from "../utils/logger.mjs";
|
|
2
|
+
import { dictionaryFrom } from "../translators/api.mjs";
|
|
3
|
+
import { createCache } from "../translators/cache-factory.mjs";
|
|
4
|
+
import { TranslationService } from "../translators/translation-service.mjs";
|
|
5
|
+
import { loadMetadata } from "../metadata/manager.mjs";
|
|
6
|
+
import { startTranslationServer } from "../translation-server/translation-server.mjs";
|
|
7
|
+
import fs from "fs/promises";
|
|
8
|
+
import path from "path";
|
|
9
|
+
|
|
10
|
+
//#region src/plugin/build-translator.ts
|
|
11
|
+
/**
|
|
12
|
+
* Build-time translation processor
|
|
13
|
+
*
|
|
14
|
+
* Handles translation generation and validation at build time
|
|
15
|
+
* Supports two modes:
|
|
16
|
+
* - "translate": Generate all translations, fail if translation fails
|
|
17
|
+
* - "cache-only": Validate cache completeness, fail if incomplete
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* Process translations at build time
|
|
21
|
+
*
|
|
22
|
+
* @throws Error if validation or translation fails (causes build to fail)
|
|
23
|
+
*/
|
|
24
|
+
async function processBuildTranslations(options) {
|
|
25
|
+
const { config, publicOutputPath, metadataFilePath } = options;
|
|
26
|
+
const buildMode = process.env.WEGLOT_BUILD_MODE || config.buildMode;
|
|
27
|
+
logger.info(`🌍 Build mode: ${buildMode}`);
|
|
28
|
+
const metadata = await loadMetadata(metadataFilePath, true);
|
|
29
|
+
if (!metadata || Object.keys(metadata).length === 0) {
|
|
30
|
+
logger.info("No translations to process (metadata is empty)");
|
|
31
|
+
return {
|
|
32
|
+
success: true,
|
|
33
|
+
stats: {}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const totalEntries = Object.keys(metadata).length;
|
|
37
|
+
logger.info(`📊 Found ${totalEntries} translatable entries`);
|
|
38
|
+
const cache = createCache(config);
|
|
39
|
+
if (buildMode === "cache-only") {
|
|
40
|
+
logger.info("🔍 Validating translation cache...");
|
|
41
|
+
await validateCache(config, metadata, cache);
|
|
42
|
+
logger.info("✅ Cache validation passed");
|
|
43
|
+
if (publicOutputPath) await copyStaticFiles(config, publicOutputPath, metadata, cache);
|
|
44
|
+
return {
|
|
45
|
+
success: true,
|
|
46
|
+
stats: buildCacheStats(config, metadata)
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
logger.info("🔄 Generating translations...");
|
|
50
|
+
let translationServer;
|
|
51
|
+
try {
|
|
52
|
+
translationServer = await startTranslationServer({
|
|
53
|
+
translationService: new TranslationService(config, logger),
|
|
54
|
+
onError: (err) => {
|
|
55
|
+
logger.error("Translation server error:", err);
|
|
56
|
+
},
|
|
57
|
+
config
|
|
58
|
+
});
|
|
59
|
+
const allLocales = config.targetLocales;
|
|
60
|
+
logger.info(`Processing translations for ${allLocales.length} locale(s)...`);
|
|
61
|
+
const stats = {};
|
|
62
|
+
const errors = [];
|
|
63
|
+
const skipped = [];
|
|
64
|
+
const localePromises = allLocales.map(async (locale) => {
|
|
65
|
+
logger.info(`Translating to ${locale}...`);
|
|
66
|
+
const result = await translationServer.translateAll(locale);
|
|
67
|
+
stats[locale] = {
|
|
68
|
+
total: totalEntries,
|
|
69
|
+
translated: Object.keys(result.translations).length,
|
|
70
|
+
failed: result.stats.failed
|
|
71
|
+
};
|
|
72
|
+
if (result.unsupportedLocale) {
|
|
73
|
+
skipped.push(locale);
|
|
74
|
+
if (!await cache.has(locale)) await cache.set(locale, {});
|
|
75
|
+
logger.warn(`⏭️ Skipped ${locale}: the Weglot API does not translate ${config.sourceLocale} to ${locale}. Remove the language from the project or ask Weglot support to enable the pair.`);
|
|
76
|
+
} else if (result.errors.length > 0) {
|
|
77
|
+
logger.warn(`⚠️ ${result.errors.length} translation error(s) for ${locale}`);
|
|
78
|
+
errors.push({
|
|
79
|
+
locale,
|
|
80
|
+
error: `${result.errors.length} translation(s) failed`
|
|
81
|
+
});
|
|
82
|
+
} else logger.info(`✅ ${locale} completed successfully`);
|
|
83
|
+
});
|
|
84
|
+
await Promise.all(localePromises);
|
|
85
|
+
if (errors.length > 0) {
|
|
86
|
+
const errorMsg = formatTranslationErrors(errors);
|
|
87
|
+
logger.error(errorMsg);
|
|
88
|
+
process.exit(1);
|
|
89
|
+
}
|
|
90
|
+
if (publicOutputPath) await copyStaticFiles(config, publicOutputPath, metadata, cache);
|
|
91
|
+
if (skipped.length > 0) logger.warn(`✅ Translation generation completed, without ${skipped.join(", ")}`);
|
|
92
|
+
else logger.info("✅ Translation generation completed successfully");
|
|
93
|
+
return {
|
|
94
|
+
success: true,
|
|
95
|
+
stats
|
|
96
|
+
};
|
|
97
|
+
} catch (error) {
|
|
98
|
+
logger.error("❌ Translation generation failed:\n", error instanceof Error ? error.message : error);
|
|
99
|
+
process.exit(1);
|
|
100
|
+
} finally {
|
|
101
|
+
if (translationServer) {
|
|
102
|
+
await translationServer.stop();
|
|
103
|
+
logger.info("✅ Translation server stopped");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Validate that all required translations exist in cache
|
|
109
|
+
* @throws Error if cache is incomplete or missing
|
|
110
|
+
*/
|
|
111
|
+
async function validateCache(config, metadata, cache) {
|
|
112
|
+
const allHashes = Object.keys(metadata);
|
|
113
|
+
const missingLocales = [];
|
|
114
|
+
const incompleteLocales = [];
|
|
115
|
+
const allLocales = config.targetLocales;
|
|
116
|
+
for (const locale of allLocales) try {
|
|
117
|
+
const entries = await cache.get(locale);
|
|
118
|
+
if (Object.keys(entries).length === 0) {
|
|
119
|
+
if (await cache.has(locale)) {
|
|
120
|
+
logger.warn(`⏭️ ${locale} holds no translations and is served untranslated`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
missingLocales.push(locale);
|
|
124
|
+
logger.debug(`Cache file not found for ${locale}`);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const missingHashes = allHashes.filter((hash) => !entries[hash]);
|
|
128
|
+
if (missingHashes.length > 0) {
|
|
129
|
+
incompleteLocales.push({
|
|
130
|
+
locale,
|
|
131
|
+
missing: missingHashes.length,
|
|
132
|
+
total: allHashes.length
|
|
133
|
+
});
|
|
134
|
+
logger.debug(`Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(", ")}${missingHashes.length > 5 ? "..." : ""}`);
|
|
135
|
+
}
|
|
136
|
+
} catch (error) {
|
|
137
|
+
missingLocales.push(locale);
|
|
138
|
+
logger.debug(`Failed to read cache for ${locale}:`, error);
|
|
139
|
+
}
|
|
140
|
+
if (missingLocales.length > 0 || incompleteLocales.length > 0) {
|
|
141
|
+
const errorMsg = formatCacheValidationError(missingLocales, incompleteLocales);
|
|
142
|
+
logger.error(errorMsg);
|
|
143
|
+
process.exit(1);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function buildCacheStats(config, metadata) {
|
|
147
|
+
const totalEntries = Object.keys(metadata).length;
|
|
148
|
+
const stats = {};
|
|
149
|
+
const allLocales = config.targetLocales;
|
|
150
|
+
for (const locale of allLocales) stats[locale] = {
|
|
151
|
+
total: totalEntries,
|
|
152
|
+
translated: totalEntries,
|
|
153
|
+
failed: 0
|
|
154
|
+
};
|
|
155
|
+
return stats;
|
|
156
|
+
}
|
|
157
|
+
async function copyStaticFiles(config, publicOutputPath, metadata, cache) {
|
|
158
|
+
logger.info(`📦 Generating static translation files in ${publicOutputPath}`);
|
|
159
|
+
await fs.mkdir(publicOutputPath, { recursive: true });
|
|
160
|
+
const usedHashes = new Set(Object.keys(metadata));
|
|
161
|
+
logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);
|
|
162
|
+
const allLocales = config.targetLocales;
|
|
163
|
+
for (const locale of allLocales) {
|
|
164
|
+
const publicFilePath = path.join(publicOutputPath, `${locale}.json`);
|
|
165
|
+
try {
|
|
166
|
+
const entries = await cache.get(locale, Array.from(usedHashes));
|
|
167
|
+
const outputData = dictionaryFrom(locale, entries);
|
|
168
|
+
await fs.writeFile(publicFilePath, JSON.stringify(outputData, null, 2), "utf-8");
|
|
169
|
+
logger.info(`✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`);
|
|
170
|
+
} catch (error) {
|
|
171
|
+
logger.error(`❌ Failed to generate ${locale}.json:`, error);
|
|
172
|
+
process.exit(1);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function formatCacheValidationError(missingLocales, incompleteLocales) {
|
|
177
|
+
let msg = "❌ Cache validation failed in cache-only mode:\n\n";
|
|
178
|
+
if (missingLocales.length > 0) {
|
|
179
|
+
msg += ` 📁 Missing cache files:\n`;
|
|
180
|
+
msg += missingLocales.map((locale) => ` - ${locale}.json`).join("\n");
|
|
181
|
+
msg += "\n\n";
|
|
182
|
+
}
|
|
183
|
+
if (incompleteLocales.length > 0) {
|
|
184
|
+
msg += ` 📊 Incomplete cache:\n`;
|
|
185
|
+
msg += incompleteLocales.map((item) => ` - ${item.locale}: ${item.missing}/${item.total} translations missing`).join("\n");
|
|
186
|
+
msg += "\n\n";
|
|
187
|
+
}
|
|
188
|
+
msg += ` 💡 To fix:\n`;
|
|
189
|
+
msg += ` 1. Set WEGLOT_BUILD_MODE=translate to generate translations\n`;
|
|
190
|
+
msg += ` 2. Commit the generated weglot/cache/*.json files\n`;
|
|
191
|
+
msg += ` 3. Ensure translation API keys are available if generating translations`;
|
|
192
|
+
return msg;
|
|
193
|
+
}
|
|
194
|
+
function formatTranslationErrors(errors) {
|
|
195
|
+
let msg = "❌ Translation generation failed:\n\n";
|
|
196
|
+
msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join("\n");
|
|
197
|
+
msg += "\n\n";
|
|
198
|
+
msg += ` 💡 Translation errors must be resolved in "translate" mode.\n`;
|
|
199
|
+
msg += ` Check translation server logs for details.`;
|
|
200
|
+
return msg;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
//#endregion
|
|
204
|
+
export { processBuildTranslations };
|
|
205
|
+
//# sourceMappingURL=build-translator.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-translator.mjs","names":["translationServer: TranslationServer | undefined","stats: BuildTranslationResult[\"stats\"]","errors: Array<{ locale: LocaleCode; error: string }>","skipped: LocaleCode[]","missingLocales: string[]","incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>"],"sources":["../../src/plugin/build-translator.ts"],"sourcesContent":["/**\n * Build-time translation processor\n *\n * Handles translation generation and validation at build time\n * Supports two modes:\n * - \"translate\": Generate all translations, fail if translation fails\n * - \"cache-only\": Validate cache completeness, fail if incomplete\n */\n// TODO (AleksandrSl 08/12/2025): Add ICU validation for messages? The problem is that we don't know which will be rendered as a simple text\nimport fs from \"fs/promises\";\nimport path from \"path\";\nimport type { WeglotConfig, MetadataSchema } from \"../types\";\nimport { logger } from \"../utils/logger\";\nimport {\n startTranslationServer,\n type TranslationServer,\n} from \"../translation-server\";\nimport { loadMetadata } from \"../metadata/manager\";\nimport {\n createCache,\n type TranslationCache,\n TranslationService,\n} from \"../translators\";\nimport { dictionaryFrom } from \"../translators/api\";\nimport type { LocaleCode } from \"../locale\";\n\nexport interface BuildTranslationOptions {\n config: WeglotConfig;\n publicOutputPath: string;\n metadataFilePath: string;\n}\n\nexport interface BuildTranslationResult {\n /**\n * Whether the build succeeded\n */\n success: boolean;\n\n /**\n * Error message if build failed\n */\n error?: string;\n\n /**\n * Translation statistics per locale\n */\n stats: Record<\n string,\n {\n total: number;\n translated: number;\n failed: number;\n }\n >;\n}\n\n/**\n * Process translations at build time\n *\n * @throws Error if validation or translation fails (causes build to fail)\n */\nexport async function processBuildTranslations(\n options: BuildTranslationOptions,\n): Promise<BuildTranslationResult> {\n const { config, publicOutputPath, metadataFilePath } = options;\n\n // Determine build mode (env var > options > config)\n const buildMode =\n (process.env.WEGLOT_BUILD_MODE as \"translate\" | \"cache-only\") ||\n config.buildMode;\n\n logger.info(`🌍 Build mode: ${buildMode}`);\n\n const metadata = await loadMetadata(metadataFilePath, true);\n\n if (!metadata || Object.keys(metadata).length === 0) {\n logger.info(\"No translations to process (metadata is empty)\");\n return {\n success: true,\n stats: {},\n };\n }\n\n const totalEntries = Object.keys(metadata).length;\n logger.info(`📊 Found ${totalEntries} translatable entries`);\n\n const cache = createCache(config);\n\n // Handle cache-only mode\n if (buildMode === \"cache-only\") {\n logger.info(\"🔍 Validating translation cache...\");\n await validateCache(config, metadata, cache);\n logger.info(\"✅ Cache validation passed\");\n\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n return {\n success: true,\n stats: buildCacheStats(config, metadata),\n };\n }\n\n // Handle translate mode\n logger.info(\"🔄 Generating translations...\");\n let translationServer: TranslationServer | undefined;\n\n try {\n translationServer = await startTranslationServer({\n translationService: new TranslationService(config, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n config,\n });\n\n const allLocales = config.targetLocales;\n\n logger.info(`Processing translations for ${allLocales.length} locale(s)...`);\n\n const stats: BuildTranslationResult[\"stats\"] = {};\n const errors: Array<{ locale: LocaleCode; error: string }> = [];\n const skipped: LocaleCode[] = [];\n\n // Translate all locales in parallel\n const localePromises = allLocales.map(async (locale) => {\n logger.info(`Translating to ${locale}...`);\n\n const result = await translationServer!.translateAll(locale);\n\n stats[locale] = {\n total: totalEntries,\n translated: Object.keys(result.translations).length,\n failed: result.stats.failed,\n };\n\n if (result.unsupportedLocale) {\n // Not a build failure: the pair is refused, so the locale is served as source.\n skipped.push(locale);\n // An empty dictionary marks the locale deliberately untranslated. Never\n // overwrite one: an earlier run may hold real translations.\n if (!(await cache.has(locale))) {\n await cache.set(locale, {});\n }\n logger.warn(\n `⏭️ Skipped ${locale}: the Weglot API does not translate ${config.sourceLocale} to ${locale}. Remove the language from the project or ask Weglot support to enable the pair.`,\n );\n } else if (result.errors.length > 0) {\n logger.warn(\n `⚠️ ${result.errors.length} translation error(s) for ${locale}`,\n );\n errors.push({\n locale,\n error: `${result.errors.length} translation(s) failed`,\n });\n } else {\n logger.info(`✅ ${locale} completed successfully`);\n }\n });\n\n await Promise.all(localePromises);\n\n // Fail build if any translations failed in translate mode\n if (errors.length > 0) {\n const errorMsg = formatTranslationErrors(errors);\n logger.error(errorMsg);\n process.exit(1);\n }\n\n // Copy cache to public directory if requested\n if (publicOutputPath) {\n await copyStaticFiles(config, publicOutputPath, metadata, cache);\n }\n\n if (skipped.length > 0) {\n logger.warn(\n `✅ Translation generation completed, without ${skipped.join(\", \")}`,\n );\n } else {\n logger.info(\"✅ Translation generation completed successfully\");\n }\n\n return {\n success: true,\n stats,\n };\n } catch (error) {\n logger.error(\n \"❌ Translation generation failed:\\n\",\n error instanceof Error ? error.message : error,\n );\n process.exit(1);\n } finally {\n if (translationServer) {\n await translationServer.stop();\n logger.info(\"✅ Translation server stopped\");\n }\n }\n}\n\n/**\n * Validate that all required translations exist in cache\n * @throws Error if cache is incomplete or missing\n */\nasync function validateCache(\n config: WeglotConfig,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n const allHashes = Object.keys(metadata);\n const missingLocales: string[] = [];\n const incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }> = [];\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n try {\n const entries = await cache.get(locale);\n\n if (Object.keys(entries).length === 0) {\n // Emptiness is deliberate: an untranslatable locale still gets a file.\n if (await cache.has(locale)) {\n logger.warn(\n `⏭️ ${locale} holds no translations and is served untranslated`,\n );\n continue;\n }\n missingLocales.push(locale);\n logger.debug(`Cache file not found for ${locale}`);\n continue;\n }\n\n const missingHashes = allHashes.filter((hash) => !entries[hash]);\n\n if (missingHashes.length > 0) {\n incompleteLocales.push({\n locale,\n missing: missingHashes.length,\n total: allHashes.length,\n });\n\n // Log first few missing hashes for debugging\n logger.debug(\n `Missing hashes in ${locale}: ${missingHashes.slice(0, 5).join(\", \")}${\n missingHashes.length > 5 ? \"...\" : \"\"\n }`,\n );\n }\n } catch (error) {\n missingLocales.push(locale);\n logger.debug(`Failed to read cache for ${locale}:`, error);\n }\n }\n\n if (missingLocales.length > 0 || incompleteLocales.length > 0) {\n const errorMsg = formatCacheValidationError(\n missingLocales,\n incompleteLocales,\n );\n logger.error(errorMsg);\n process.exit(1);\n }\n}\n\nfunction buildCacheStats(\n config: WeglotConfig,\n metadata: MetadataSchema,\n): BuildTranslationResult[\"stats\"] {\n const totalEntries = Object.keys(metadata).length;\n const stats: BuildTranslationResult[\"stats\"] = {};\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n stats[locale] = {\n total: totalEntries,\n translated: totalEntries, // Assumed complete if validation passed\n failed: 0,\n };\n }\n\n return stats;\n}\n\nasync function copyStaticFiles(\n config: WeglotConfig,\n publicOutputPath: string,\n metadata: MetadataSchema,\n cache: TranslationCache,\n): Promise<void> {\n logger.info(`📦 Generating static translation files in ${publicOutputPath}`);\n\n await fs.mkdir(publicOutputPath, { recursive: true });\n\n const usedHashes = new Set(Object.keys(metadata));\n logger.info(`📊 Filtering translations to ${usedHashes.size} used hash(es)`);\n\n const allLocales = config.targetLocales;\n\n for (const locale of allLocales) {\n const publicFilePath = path.join(publicOutputPath, `${locale}.json`);\n\n try {\n const entries = await cache.get(locale, Array.from(usedHashes));\n const outputData = dictionaryFrom(locale, entries);\n\n await fs.writeFile(\n publicFilePath,\n JSON.stringify(outputData, null, 2),\n \"utf-8\",\n );\n\n logger.info(\n `✓ Generated ${locale}.json (${Object.keys(entries).length} translations)`,\n );\n } catch (error) {\n logger.error(`❌ Failed to generate ${locale}.json:`, error);\n process.exit(1);\n }\n }\n}\n\nfunction formatCacheValidationError(\n missingLocales: string[],\n incompleteLocales: Array<{\n locale: LocaleCode;\n missing: number;\n total: number;\n }>,\n): string {\n let msg = \"❌ Cache validation failed in cache-only mode:\\n\\n\";\n\n if (missingLocales.length > 0) {\n msg += ` 📁 Missing cache files:\\n`;\n msg += missingLocales.map((locale) => ` - ${locale}.json`).join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n if (incompleteLocales.length > 0) {\n msg += ` 📊 Incomplete cache:\\n`;\n msg += incompleteLocales\n .map(\n (item) =>\n ` - ${item.locale}: ${item.missing}/${item.total} translations missing`,\n )\n .join(\"\\n\");\n msg += \"\\n\\n\";\n }\n\n msg += ` 💡 To fix:\\n`;\n msg += ` 1. Set WEGLOT_BUILD_MODE=translate to generate translations\\n`;\n msg += ` 2. Commit the generated weglot/cache/*.json files\\n`;\n msg += ` 3. Ensure translation API keys are available if generating translations`;\n\n return msg;\n}\n\nfunction formatTranslationErrors(\n errors: Array<{ locale: LocaleCode; error: string }>,\n): string {\n let msg = \"❌ Translation generation failed:\\n\\n\";\n\n msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join(\"\\n\");\n\n msg += \"\\n\\n\";\n msg += ` 💡 Translation errors must be resolved in \"translate\" mode.\\n`;\n msg += ` Check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EAC/B,MAAM,iBAAiB,KAAK,KAAK,kBAAkB,GAAG,OAAO,OAAO;AAEpE,MAAI;GACF,MAAM,UAAU,MAAM,MAAM,IAAI,QAAQ,MAAM,KAAK,WAAW,CAAC;GAC/D,MAAM,aAAa,eAAe,QAAQ,QAAQ;AAElD,SAAM,GAAG,UACP,gBACA,KAAK,UAAU,YAAY,MAAM,EAAE,EACnC,QACD;AAED,UAAO,KACL,eAAe,OAAO,SAAS,OAAO,KAAK,QAAQ,CAAC,OAAO,gBAC5D;WACM,OAAO;AACd,UAAO,MAAM,wBAAwB,OAAO,SAAS,MAAM;AAC3D,WAAQ,KAAK,EAAE;;;;AAKrB,SAAS,2BACP,gBACA,mBAKQ;CACR,IAAI,MAAM;AAEV,KAAI,eAAe,SAAS,GAAG;AAC7B,SAAO;AACP,SAAO,eAAe,KAAK,WAAW,SAAS,OAAO,OAAO,CAAC,KAAK,KAAK;AACxE,SAAO;;AAGT,KAAI,kBAAkB,SAAS,GAAG;AAChC,SAAO;AACP,SAAO,kBACJ,KACE,SACC,SAAS,KAAK,OAAO,IAAI,KAAK,QAAQ,GAAG,KAAK,MAAM,uBACvD,CACA,KAAK,KAAK;AACb,SAAO;;AAGT,QAAO;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO;;AAGT,SAAS,wBACP,QACQ;CACR,IAAI,MAAM;AAEV,QAAO,OAAO,KAAK,QAAQ,OAAO,IAAI,OAAO,IAAI,IAAI,QAAQ,CAAC,KAAK,KAAK;AAExE,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/plugin/cleanup.ts
|
|
3
|
+
function registerCleanupOnCurrentProcess({ cleanup, asyncCleanup }) {
|
|
4
|
+
if (asyncCleanup) {
|
|
5
|
+
let shuttingDown = false;
|
|
6
|
+
async function performGracefulShutdown(code) {
|
|
7
|
+
if (shuttingDown) return;
|
|
8
|
+
shuttingDown = true;
|
|
9
|
+
await asyncCleanup?.();
|
|
10
|
+
process.exit(code);
|
|
11
|
+
}
|
|
12
|
+
process.on("SIGINT", () => performGracefulShutdown(0));
|
|
13
|
+
process.on("SIGTERM", () => performGracefulShutdown(143));
|
|
14
|
+
process.on("SIGBREAK", () => performGracefulShutdown(0));
|
|
15
|
+
}
|
|
16
|
+
if (cleanup) process.on("exit", () => cleanup());
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
//#endregion
|
|
20
|
+
exports.registerCleanupOnCurrentProcess = registerCleanupOnCurrentProcess;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/plugin/cleanup.ts
|
|
2
|
+
function registerCleanupOnCurrentProcess({ cleanup, asyncCleanup }) {
|
|
3
|
+
if (asyncCleanup) {
|
|
4
|
+
let shuttingDown = false;
|
|
5
|
+
async function performGracefulShutdown(code) {
|
|
6
|
+
if (shuttingDown) return;
|
|
7
|
+
shuttingDown = true;
|
|
8
|
+
await asyncCleanup?.();
|
|
9
|
+
process.exit(code);
|
|
10
|
+
}
|
|
11
|
+
process.on("SIGINT", () => performGracefulShutdown(0));
|
|
12
|
+
process.on("SIGTERM", () => performGracefulShutdown(143));
|
|
13
|
+
process.on("SIGBREAK", () => performGracefulShutdown(0));
|
|
14
|
+
}
|
|
15
|
+
if (cleanup) process.on("exit", () => cleanup());
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
export { registerCleanupOnCurrentProcess };
|
|
20
|
+
//# sourceMappingURL=cleanup.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cleanup.mjs","names":[],"sources":["../../src/plugin/cleanup.ts"],"sourcesContent":["export function registerCleanupOnCurrentProcess({\n cleanup,\n asyncCleanup,\n}: {\n cleanup?: () => void;\n asyncCleanup?: () => Promise<void>;\n}) {\n if (asyncCleanup) {\n let shuttingDown = false;\n async function performGracefulShutdown(code: number) {\n if (shuttingDown) return;\n shuttingDown = true;\n\n await asyncCleanup?.();\n\n process.exit(code);\n }\n\n process.on(\"SIGINT\", () => performGracefulShutdown(0));\n process.on(\"SIGTERM\", () => performGracefulShutdown(143));\n process.on(\"SIGBREAK\", () => performGracefulShutdown(0));\n }\n\n if (cleanup) {\n process.on(\"exit\", () => cleanup());\n }\n}\n"],"mappings":";AAAA,SAAgB,gCAAgC,EAC9C,SACA,gBAIC;AACD,KAAI,cAAc;EAChB,IAAI,eAAe;EACnB,eAAe,wBAAwB,MAAc;AACnD,OAAI,aAAc;AAClB,kBAAe;AAEf,SAAM,gBAAgB;AAEtB,WAAQ,KAAK,KAAK;;AAGpB,UAAQ,GAAG,gBAAgB,wBAAwB,EAAE,CAAC;AACtD,UAAQ,GAAG,iBAAiB,wBAAwB,IAAI,CAAC;AACzD,UAAQ,GAAG,kBAAkB,wBAAwB,EAAE,CAAC;;AAG1D,KAAI,QACF,SAAQ,GAAG,cAAc,SAAS,CAAC"}
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|