@weglot/translate-react 0.2.0 → 0.2.2
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 +78 -15
- package/build/metadata/manager.cjs +18 -5
- package/build/metadata/manager.mjs +17 -5
- package/build/metadata/manager.mjs.map +1 -1
- package/build/plugin/build-translator.cjs +2 -1
- package/build/plugin/build-translator.mjs +2 -1
- package/build/plugin/build-translator.mjs.map +1 -1
- package/build/plugin/next-compiler-loader.cjs +1 -4
- package/build/plugin/next-compiler-loader.mjs +2 -5
- package/build/plugin/next-compiler-loader.mjs.map +1 -1
- package/build/plugin/next-traces.cjs +38 -0
- package/build/plugin/next-traces.mjs +36 -0
- package/build/plugin/next-traces.mjs.map +1 -0
- package/build/plugin/next.cjs +30 -10
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +28 -11
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/transform/process-file.cjs +9 -0
- package/build/plugin/transform/process-file.mjs +9 -0
- package/build/plugin/transform/process-file.mjs.map +1 -1
- package/build/plugin/unplugin.cjs +3 -5
- package/build/plugin/unplugin.mjs +4 -6
- package/build/plugin/unplugin.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.mts +2 -2
- package/build/react/shared/LocaleSwitcher.d.mts +2 -2
- package/build/react/shared/WeglotContext.cjs +18 -2
- package/build/react/shared/WeglotContext.d.cts +1 -0
- package/build/react/shared/WeglotContext.d.cts.map +1 -1
- package/build/react/shared/WeglotContext.d.mts +1 -0
- package/build/react/shared/WeglotContext.d.mts.map +1 -1
- package/build/react/shared/WeglotContext.mjs +18 -2
- package/build/react/shared/WeglotContext.mjs.map +1 -1
- package/build/react/shared/WeglotProvider.cjs +4 -0
- package/build/react/shared/WeglotProvider.d.cts.map +1 -1
- package/build/react/shared/WeglotProvider.d.mts +2 -2
- package/build/react/shared/WeglotProvider.d.mts.map +1 -1
- package/build/react/shared/WeglotProvider.mjs +4 -0
- package/build/react/shared/WeglotProvider.mjs.map +1 -1
- package/build/runtime/translate-dynamic.cjs +1 -1
- package/build/runtime/translate-dynamic.mjs +1 -1
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/translation-service.cjs +3 -2
- package/build/translators/translation-service.mjs +3 -2
- package/build/translators/translation-service.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +62 -34
- package/build/translators/weglot/api-client.mjs +62 -34
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/build/translators/weglot/translator.cjs +19 -1
- package/build/translators/weglot/translator.mjs +19 -1
- package/build/translators/weglot/translator.mjs.map +1 -1
- package/build/types.d.cts +7 -1
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +7 -1
- package/build/types.d.mts.map +1 -1
- package/build/utils/package-version.cjs +12 -0
- package/build/utils/package-version.mjs +12 -0
- package/build/utils/package-version.mjs.map +1 -0
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -9,13 +9,19 @@ target languages are read from your Weglot project settings, and
|
|
|
9
9
|
translations appear in your Weglot dashboard where you can review and edit
|
|
10
10
|
them.
|
|
11
11
|
|
|
12
|
+
## Requirements
|
|
13
|
+
|
|
14
|
+
- React 19, with Vite, Webpack or Next.js 15/16
|
|
15
|
+
- Node.js 20.9 or later
|
|
16
|
+
- A Weglot project: its key is in your Weglot dashboard
|
|
17
|
+
|
|
12
18
|
## Getting started
|
|
13
19
|
|
|
14
20
|
```bash
|
|
15
|
-
npm install @weglot/translate-react
|
|
21
|
+
npm install @weglot/translate-react
|
|
16
22
|
```
|
|
17
23
|
|
|
18
|
-
Set your project key in `.env
|
|
24
|
+
Set your project key in `.env`, and keep that file out of version control:
|
|
19
25
|
|
|
20
26
|
```bash
|
|
21
27
|
WEGLOT_API_KEY=your_weglot_project_key
|
|
@@ -44,6 +50,9 @@ root.render(
|
|
|
44
50
|
);
|
|
45
51
|
```
|
|
46
52
|
|
|
53
|
+
Webpack works the same way, with `weglotPlugin` from
|
|
54
|
+
`@weglot/translate-react/webpack`.
|
|
55
|
+
|
|
47
56
|
### Next.js
|
|
48
57
|
|
|
49
58
|
```ts
|
|
@@ -57,7 +66,52 @@ export default async function (): Promise<NextConfig> {
|
|
|
57
66
|
}
|
|
58
67
|
```
|
|
59
68
|
|
|
60
|
-
Wrap your root layout with `WeglotProvider
|
|
69
|
+
Wrap your root layout with the Next.js `WeglotProvider`:
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
// app/layout.tsx
|
|
73
|
+
import { WeglotProvider } from "@weglot/translate-react/react/next";
|
|
74
|
+
|
|
75
|
+
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
76
|
+
return (
|
|
77
|
+
<html>
|
|
78
|
+
<body>
|
|
79
|
+
<WeglotProvider>{children}</WeglotProvider>
|
|
80
|
+
</body>
|
|
81
|
+
</html>
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`global-not-found.tsx` renders outside the root layout, so the client
|
|
87
|
+
components it uses stay in the source language. Wrap its content in
|
|
88
|
+
`WeglotProvider` too to translate them.
|
|
89
|
+
|
|
90
|
+
### Generated files
|
|
91
|
+
|
|
92
|
+
- `<sourceRoot>/weglot/cache/<locale>.json`: the translations received from
|
|
93
|
+
Weglot. Commit it to build without calling the API (see `cache-only` below),
|
|
94
|
+
or ignore it and let each build fetch what it lacks.
|
|
95
|
+
- `public/translations/<locale>.json`: written by every build. Add it to
|
|
96
|
+
`.gitignore`.
|
|
97
|
+
|
|
98
|
+
### Switching language
|
|
99
|
+
|
|
100
|
+
The visitor's language is kept in a `locale` cookie; URLs do not change. Let
|
|
101
|
+
visitors pick it with `LocaleSwitcher`:
|
|
102
|
+
|
|
103
|
+
```tsx
|
|
104
|
+
import { LocaleSwitcher } from "@weglot/translate-react/react";
|
|
105
|
+
|
|
106
|
+
<LocaleSwitcher
|
|
107
|
+
locales={[
|
|
108
|
+
{ code: "en", label: "English" },
|
|
109
|
+
{ code: "fr", label: "Français" },
|
|
110
|
+
]}
|
|
111
|
+
/>
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Or build your own with `useWeglotContext()` (see React API).
|
|
61
115
|
|
|
62
116
|
## What gets translated
|
|
63
117
|
|
|
@@ -129,8 +183,12 @@ Languages are not configured here: they come from your Weglot project.
|
|
|
129
183
|
Weglot generates translations with an LLM, so new strings can take a moment:
|
|
130
184
|
the build waits for them up to `translationTimeout`. If some are still not
|
|
131
185
|
ready, the build fails, keeping the ones it received in the local cache, so
|
|
132
|
-
building again
|
|
133
|
-
|
|
186
|
+
building again picks up where it stopped. In dev, strings not ready in time
|
|
187
|
+
show in the source language until the next reload.
|
|
188
|
+
|
|
189
|
+
A string Weglot will not translate, such as one made only of digits, does not
|
|
190
|
+
fail the build: it is served in the source language with a warning, and asked
|
|
191
|
+
for again on the next build.
|
|
134
192
|
|
|
135
193
|
## React API
|
|
136
194
|
|
|
@@ -184,16 +242,21 @@ pnpm --filter @weglot/translate-react test
|
|
|
184
242
|
pnpm --filter @weglot/translate-react build
|
|
185
243
|
```
|
|
186
244
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
245
|
+
`pnpm test:e2e` packs the package, installs it in the fixture apps of `e2e/`
|
|
246
|
+
(Next 15, Next 16, Vite and webpack) and builds, serves and runs their dev
|
|
247
|
+
servers against a local fake of the Weglot API, so it needs no key. Browser
|
|
248
|
+
checks use Playwright's Chromium: run `pnpm exec playwright install chromium`
|
|
249
|
+
once. The installs are kept in
|
|
250
|
+
`$TMPDIR/weglot-translate-react-e2e` (or `E2E_WORK_DIR`) and reused until the
|
|
251
|
+
package or `e2e/installs/` changes. A known bug is written as `it.fails`
|
|
252
|
+
with its issue number: the PR that fixes it turns it into `it`.
|
|
253
|
+
|
|
254
|
+
`e2e/live.e2e.test.ts` builds the Next fixture against the real Weglot API and
|
|
255
|
+
is skipped without `WEGLOT_E2E_API_KEY`. The `Live API` workflow runs it on
|
|
256
|
+
every pull request and push to master, with the key from the
|
|
257
|
+
`WEGLOT_E2E_API_KEY` repository secret. A staging key also needs the
|
|
258
|
+
`WEGLOT_E2E_SETTINGS_URL` variable set to
|
|
259
|
+
`https://api.weglot.dev/project-settings`.
|
|
197
260
|
|
|
198
261
|
## License
|
|
199
262
|
|
|
@@ -61,19 +61,30 @@ async function runWithDbConnection(dbPath, noSync, fn) {
|
|
|
61
61
|
}
|
|
62
62
|
function readEntriesFromDb(db) {
|
|
63
63
|
const entries = {};
|
|
64
|
-
for (const {
|
|
64
|
+
for (const { value } of db.getRange()) {
|
|
65
|
+
const fileEntries = Array.isArray(value) ? value : [value];
|
|
66
|
+
for (const entry of fileEntries) entries[entry.hash] = entry;
|
|
67
|
+
}
|
|
65
68
|
return entries;
|
|
66
69
|
}
|
|
67
70
|
async function loadMetadata(dbPath, noSync = false) {
|
|
68
71
|
return runWithDbConnection(dbPath, noSync, readEntriesFromDb);
|
|
69
72
|
}
|
|
70
73
|
/**
|
|
71
|
-
*
|
|
74
|
+
* Replaces the entries of one file, so a string removed from it does not linger
|
|
75
|
+
* when the database is kept between builds.
|
|
72
76
|
*/
|
|
73
|
-
async function
|
|
77
|
+
async function saveFileMetadata(dbPath, filePath, entries, noSync = false) {
|
|
74
78
|
return runWithDbConnection(dbPath, noSync, (db) => {
|
|
79
|
+
if (entries.length > 0) db.putSync(filePath, entries);
|
|
80
|
+
else if (db.get(filePath) !== void 0) db.removeSync(filePath);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/** Drops the entries of files that no longer exist. */
|
|
84
|
+
async function pruneMetadata(dbPath) {
|
|
85
|
+
return runWithDbConnection(dbPath, true, (db) => {
|
|
75
86
|
db.transactionSync(() => {
|
|
76
|
-
for (const
|
|
87
|
+
for (const key of db.getKeys()) if (!fs.default.existsSync(key)) db.removeSync(key);
|
|
77
88
|
});
|
|
78
89
|
});
|
|
79
90
|
}
|
|
@@ -108,6 +119,7 @@ function cleanupMetadataForEnvironment(metadataDbPath, environment) {
|
|
|
108
119
|
cleanupExistingMetadata(metadataDbPath);
|
|
109
120
|
}
|
|
110
121
|
function getMetadataPath(config) {
|
|
122
|
+
if (config.metadataDir) return config.metadataDir;
|
|
111
123
|
const dirname = config.environment === "development" ? METADATA_DIR_DEV : METADATA_DIR_BUILD;
|
|
112
124
|
return path.default.join(require_path_helpers.getWeglotDir(config), dirname);
|
|
113
125
|
}
|
|
@@ -116,4 +128,5 @@ function getMetadataPath(config) {
|
|
|
116
128
|
exports.cleanupMetadataForEnvironment = cleanupMetadataForEnvironment;
|
|
117
129
|
exports.getMetadataPath = getMetadataPath;
|
|
118
130
|
exports.loadMetadata = loadMetadata;
|
|
119
|
-
exports.
|
|
131
|
+
exports.pruneMetadata = pruneMetadata;
|
|
132
|
+
exports.saveFileMetadata = saveFileMetadata;
|
|
@@ -58,19 +58,30 @@ async function runWithDbConnection(dbPath, noSync, fn) {
|
|
|
58
58
|
}
|
|
59
59
|
function readEntriesFromDb(db) {
|
|
60
60
|
const entries = {};
|
|
61
|
-
for (const {
|
|
61
|
+
for (const { value } of db.getRange()) {
|
|
62
|
+
const fileEntries = Array.isArray(value) ? value : [value];
|
|
63
|
+
for (const entry of fileEntries) entries[entry.hash] = entry;
|
|
64
|
+
}
|
|
62
65
|
return entries;
|
|
63
66
|
}
|
|
64
67
|
async function loadMetadata(dbPath, noSync = false) {
|
|
65
68
|
return runWithDbConnection(dbPath, noSync, readEntriesFromDb);
|
|
66
69
|
}
|
|
67
70
|
/**
|
|
68
|
-
*
|
|
71
|
+
* Replaces the entries of one file, so a string removed from it does not linger
|
|
72
|
+
* when the database is kept between builds.
|
|
69
73
|
*/
|
|
70
|
-
async function
|
|
74
|
+
async function saveFileMetadata(dbPath, filePath, entries, noSync = false) {
|
|
71
75
|
return runWithDbConnection(dbPath, noSync, (db) => {
|
|
76
|
+
if (entries.length > 0) db.putSync(filePath, entries);
|
|
77
|
+
else if (db.get(filePath) !== void 0) db.removeSync(filePath);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** Drops the entries of files that no longer exist. */
|
|
81
|
+
async function pruneMetadata(dbPath) {
|
|
82
|
+
return runWithDbConnection(dbPath, true, (db) => {
|
|
72
83
|
db.transactionSync(() => {
|
|
73
|
-
for (const
|
|
84
|
+
for (const key of db.getKeys()) if (!fs.existsSync(key)) db.removeSync(key);
|
|
74
85
|
});
|
|
75
86
|
});
|
|
76
87
|
}
|
|
@@ -105,10 +116,11 @@ function cleanupMetadataForEnvironment(metadataDbPath, environment) {
|
|
|
105
116
|
cleanupExistingMetadata(metadataDbPath);
|
|
106
117
|
}
|
|
107
118
|
function getMetadataPath(config) {
|
|
119
|
+
if (config.metadataDir) return config.metadataDir;
|
|
108
120
|
const dirname = config.environment === "development" ? METADATA_DIR_DEV : METADATA_DIR_BUILD;
|
|
109
121
|
return path.join(getWeglotDir(config), dirname);
|
|
110
122
|
}
|
|
111
123
|
|
|
112
124
|
//#endregion
|
|
113
|
-
export { cleanupMetadataForEnvironment, getMetadataPath, loadMetadata,
|
|
125
|
+
export { cleanupMetadataForEnvironment, getMetadataPath, loadMetadata, pruneMetadata, saveFileMetadata };
|
|
114
126
|
//# sourceMappingURL=manager.mjs.map
|
|
@@ -1 +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 {
|
|
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 { value } of db.getRange()) {\n // Databases written before entries were grouped by file hold one entry per key.\n const fileEntries = (Array.isArray(value) ? value : [value]) as TranslationEntry[];\n for (const entry of fileEntries) {\n entries[entry.hash] = entry;\n }\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 * Replaces the entries of one file, so a string removed from it does not linger\n * when the database is kept between builds.\n */\nexport async function saveFileMetadata(\n dbPath: string,\n filePath: string,\n entries: TranslationEntry[],\n noSync = false,\n): Promise<void> {\n return runWithDbConnection(dbPath, noSync, (db) => {\n if (entries.length > 0) {\n db.putSync(filePath, entries);\n } else if (db.get(filePath) !== undefined) {\n db.removeSync(filePath);\n }\n });\n}\n\n/** Drops the entries of files that no longer exist. */\nexport async function pruneMetadata(dbPath: string): Promise<void> {\n return runWithDbConnection(dbPath, true, (db) => {\n db.transactionSync(() => {\n for (const key of db.getKeys()) {\n if (!fs.existsSync(key as string)) db.removeSync(key);\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 if (config.metadataDir) return config.metadataDir;\n const dirname =\n config.environment === \"development\"\n ? METADATA_DI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
83
|
error: `${result.errors.length} translation(s) failed`
|
|
84
84
|
});
|
|
85
|
-
} else require_logger.logger.
|
|
85
|
+
} else if (result.stats.untranslated) require_logger.logger.warn(`⚠️ ${locale} completed, ${result.stats.untranslated} string(s) served untranslated`);
|
|
86
|
+
else require_logger.logger.info(`✅ ${locale} completed successfully`);
|
|
86
87
|
});
|
|
87
88
|
await Promise.all(localePromises);
|
|
88
89
|
if (errors.length > 0) {
|
|
@@ -79,7 +79,8 @@ async function processBuildTranslations(options) {
|
|
|
79
79
|
locale,
|
|
80
80
|
error: `${result.errors.length} translation(s) failed`
|
|
81
81
|
});
|
|
82
|
-
} else logger.
|
|
82
|
+
} else if (result.stats.untranslated) logger.warn(`⚠️ ${locale} completed, ${result.stats.untranslated} string(s) served untranslated`);
|
|
83
|
+
else logger.info(`✅ ${locale} completed successfully`);
|
|
83
84
|
});
|
|
84
85
|
await Promise.all(localePromises);
|
|
85
86
|
if (errors.length > 0) {
|
|
@@ -1 +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 += ` If Weglot was still generating translations, build again without the\\n`;\n msg += ` .next cache: the ones received are kept. Raise WEGLOT_TRANSLATION_TIMEOUT\\n`;\n msg += ` to wait longer.\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AK,MAAM,UAAU,YAAY;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;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
|
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 if (result.stats.untranslated) {\n logger.warn(\n `⚠️ ${locale} completed, ${result.stats.untranslated} string(s) served untranslated`,\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 += ` If Weglot was still generating translations, build again without the\\n`;\n msg += ` .next cache: the ones received are kept. Raise WEGLOT_TRANSLATION_TIMEOUT\\n`;\n msg += ` to wait longer.\\n`;\n msg += ` Otherwise, check translation server logs for details.`;\n\n return msg;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,yBACpB,SACiC;CACjC,MAAM,EAAE,QAAQ,kBAAkB,qBAAqB;CAGvD,MAAM,YACH,QAAQ,IAAI,qBACb,OAAO;AAET,QAAO,KAAK,kBAAkB,YAAY;CAE1C,MAAM,WAAW,MAAM,aAAa,kBAAkB,KAAK;AAE3D,KAAI,CAAC,YAAY,OAAO,KAAK,SAAS,CAAC,WAAW,GAAG;AACnD,SAAO,KAAK,iDAAiD;AAC7D,SAAO;GACL,SAAS;GACT,OAAO,EAAE;GACV;;CAGH,MAAM,eAAe,OAAO,KAAK,SAAS,CAAC;AAC3C,QAAO,KAAK,YAAY,aAAa,uBAAuB;CAE5D,MAAM,QAAQ,YAAY,OAAO;AAGjC,KAAI,cAAc,cAAc;AAC9B,SAAO,KAAK,qCAAqC;AACjD,QAAM,cAAc,QAAQ,UAAU,MAAM;AAC5C,SAAO,KAAK,4BAA4B;AAExC,MAAI,iBACF,OAAM,gBAAgB,QAAQ,kBAAkB,UAAU,MAAM;AAGlE,SAAO;GACL,SAAS;GACT,OAAO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,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;AACP,QAAO;AACP,QAAO;AACP,QAAO;AAEP,QAAO"}
|
|
@@ -22,11 +22,8 @@ async function nextCompilerLoader(source) {
|
|
|
22
22
|
filePath: this.resourcePath,
|
|
23
23
|
config
|
|
24
24
|
});
|
|
25
|
+
await require_manager.saveFileMetadata(config.metadataFilePath, this.resourcePath, result.transformed ? result.newEntries ?? [] : [], config.environment !== "development");
|
|
25
26
|
if (!result.transformed) return callback(null, source);
|
|
26
|
-
if (result.newEntries && result.newEntries.length > 0) {
|
|
27
|
-
await require_manager.saveMetadata(config.metadataFilePath, result.newEntries, config.environment !== "development");
|
|
28
|
-
require_logger.logger.debug(`[Turbopack Loader] Found ${result.newEntries.length} translatable text(s) in ${this.resourcePath}`);
|
|
29
|
-
}
|
|
30
27
|
const validMap = result.map && result.map.sources && Array.isArray(result.map.sources) && result.map.sources.every((s) => typeof s === "string") ? result.map : void 0;
|
|
31
28
|
callback(null, result.code, validMap);
|
|
32
29
|
} catch (error) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { logger } from "../utils/logger.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { saveFileMetadata } from "../metadata/manager.mjs";
|
|
3
3
|
import { transformComponent } from "./transform/index.mjs";
|
|
4
4
|
|
|
5
5
|
//#region src/plugin/next-compiler-loader.ts
|
|
@@ -22,11 +22,8 @@ async function nextCompilerLoader(source) {
|
|
|
22
22
|
filePath: this.resourcePath,
|
|
23
23
|
config
|
|
24
24
|
});
|
|
25
|
+
await saveFileMetadata(config.metadataFilePath, this.resourcePath, result.transformed ? result.newEntries ?? [] : [], config.environment !== "development");
|
|
25
26
|
if (!result.transformed) return callback(null, source);
|
|
26
|
-
if (result.newEntries && result.newEntries.length > 0) {
|
|
27
|
-
await saveMetadata(config.metadataFilePath, result.newEntries, config.environment !== "development");
|
|
28
|
-
logger.debug(`[Turbopack Loader] Found ${result.newEntries.length} translatable text(s) in ${this.resourcePath}`);
|
|
29
|
-
}
|
|
30
27
|
const validMap = result.map && result.map.sources && Array.isArray(result.map.sources) && result.map.sources.every((s) => typeof s === "string") ? result.map : void 0;
|
|
31
28
|
callback(null, result.code, validMap);
|
|
32
29
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next-compiler-loader.mjs","names":["config: WeglotConfig & { metadataFilePath: string }"],"sources":["../../src/plugin/next-compiler-loader.ts"],"sourcesContent":["import type { WeglotConfig } from \"../types\";\nimport { transformComponent } from \"./transform\";\nimport { logger } from \"../utils/logger\";\nimport {
|
|
1
|
+
{"version":3,"file":"next-compiler-loader.mjs","names":["config: WeglotConfig & { metadataFilePath: string }"],"sources":["../../src/plugin/next-compiler-loader.ts"],"sourcesContent":["import type { WeglotConfig } from \"../types\";\nimport { transformComponent } from \"./transform\";\nimport { logger } from \"../utils/logger\";\nimport { saveFileMetadata } from \"../metadata/manager\";\n\n/**\n * Turbopack/Webpack loader for automatic translation\n *\n * This loader transforms React components to inject translation calls automatically.\n *\n * For production builds, translations are generated after compilation completes\n * via Next.js's runAfterProductionCompile hook (see next.ts plugin).\n */\nexport default async function nextCompilerLoader(\n this: any,\n source: string,\n): Promise<void> {\n // TODO (AleksandrSl 14/12/2025): Webpack doesn't like callback usage in async function.\n // But async function can return only code, so we have to use promises which is sad. It actually errors only when we catch an error, so it's not an urgent problem\n\n // Ensure we're running in loader context\n if (typeof this.async !== \"function\") {\n throw new Error(\"This module must be run as a loader\");\n }\n const callback = this.async();\n\n try {\n const config: WeglotConfig & { metadataFilePath: string } =\n this.getOptions();\n\n logger.debug(`[Turbopack Loader] Processing: ${this.resourcePath}`);\n\n // Transform the component\n const result = transformComponent({\n code: source,\n filePath: this.resourcePath,\n config,\n });\n\n await saveFileMetadata(\n config.metadataFilePath,\n this.resourcePath,\n result.transformed ? (result.newEntries ?? []) : [],\n config.environment !== \"development\",\n );\n\n if (!result.transformed) {\n return callback(null, source);\n }\n\n // Validate source map before passing to webpack\n // Webpack crashes if sources array contains undefined values\n const validMap =\n result.map &&\n result.map.sources &&\n Array.isArray(result.map.sources) &&\n result.map.sources.every((s: any) => typeof s === \"string\")\n ? result.map\n : undefined;\n\n callback(null, result.code, validMap);\n } catch (error) {\n logger.error(`Compiler failed for ${this.resourcePath}:`);\n logger.error(\n \"Details:\",\n error,\n typeof error === \"object\" && error && \"message\" in error\n ? error.message\n : error,\n error instanceof Error ? error.stack : undefined,\n );\n callback(error as Error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,eAA8B,mBAE5B,QACe;AAKf,KAAI,OAAO,KAAK,UAAU,WACxB,OAAM,IAAI,MAAM,sCAAsC;CAExD,MAAM,WAAW,KAAK,OAAO;AAE7B,KAAI;EACF,MAAMA,SACJ,KAAK,YAAY;AAEnB,SAAO,MAAM,kCAAkC,KAAK,eAAe;EAGnE,MAAM,SAAS,mBAAmB;GAChC,MAAM;GACN,UAAU,KAAK;GACf;GACD,CAAC;AAEF,QAAM,iBACJ,OAAO,kBACP,KAAK,cACL,OAAO,cAAe,OAAO,cAAc,EAAE,GAAI,EAAE,EACnD,OAAO,gBAAgB,cACxB;AAED,MAAI,CAAC,OAAO,YACV,QAAO,SAAS,MAAM,OAAO;EAK/B,MAAM,WACJ,OAAO,OACP,OAAO,IAAI,WACX,MAAM,QAAQ,OAAO,IAAI,QAAQ,IACjC,OAAO,IAAI,QAAQ,OAAO,MAAW,OAAO,MAAM,SAAS,GACvD,OAAO,MACP;AAEN,WAAS,MAAM,OAAO,MAAM,SAAS;UAC9B,OAAO;AACd,SAAO,MAAM,uBAAuB,KAAK,aAAa,GAAG;AACzD,SAAO,MACL,YACA,OACA,OAAO,UAAU,YAAY,SAAS,aAAa,QAC/C,MAAM,UACN,OACJ,iBAAiB,QAAQ,MAAM,QAAQ,OACxC;AACD,WAAS,MAAe"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_fs_promises = require("node:fs/promises");
|
|
3
|
+
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
4
|
+
let node_path = require("node:path");
|
|
5
|
+
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
6
|
+
|
|
7
|
+
//#region src/plugin/next-traces.ts
|
|
8
|
+
async function findTraceFiles(dir) {
|
|
9
|
+
const entries = await node_fs_promises.default.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
10
|
+
return (await Promise.all(entries.map((entry) => {
|
|
11
|
+
const fullPath = node_path.default.join(dir, entry.name);
|
|
12
|
+
if (entry.isDirectory()) return findTraceFiles(fullPath);
|
|
13
|
+
return entry.name.endsWith(".nft.json") ? [fullPath] : [];
|
|
14
|
+
}))).flat();
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The server reads the dictionaries from a path built at runtime, which Next's
|
|
18
|
+
* file tracing cannot see, so standalone and Vercel builds would leave them out.
|
|
19
|
+
*/
|
|
20
|
+
async function addDictionariesToTraces(distDir, locales) {
|
|
21
|
+
const dictionaries = (await Promise.all(locales.map(async (locale) => {
|
|
22
|
+
const file = node_path.default.join(distDir, `${locale}.json`);
|
|
23
|
+
return (await node_fs_promises.default.stat(file).catch(() => null))?.isFile() ? file : null;
|
|
24
|
+
}))).filter((file) => file !== null);
|
|
25
|
+
if (dictionaries.length === 0) return;
|
|
26
|
+
const traceFiles = await findTraceFiles(node_path.default.join(distDir, "server"));
|
|
27
|
+
await Promise.all(traceFiles.map(async (traceFile) => {
|
|
28
|
+
const trace = JSON.parse(await node_fs_promises.default.readFile(traceFile, "utf8"));
|
|
29
|
+
if (!Array.isArray(trace.files)) return;
|
|
30
|
+
const files = new Set(trace.files);
|
|
31
|
+
for (const dictionary of dictionaries) files.add(node_path.default.relative(node_path.default.dirname(traceFile), dictionary).split(node_path.default.sep).join("/"));
|
|
32
|
+
trace.files = [...files];
|
|
33
|
+
await node_fs_promises.default.writeFile(traceFile, JSON.stringify(trace));
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//#endregion
|
|
38
|
+
exports.addDictionariesToTraces = addDictionariesToTraces;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region src/plugin/next-traces.ts
|
|
5
|
+
async function findTraceFiles(dir) {
|
|
6
|
+
const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
7
|
+
return (await Promise.all(entries.map((entry) => {
|
|
8
|
+
const fullPath = path.join(dir, entry.name);
|
|
9
|
+
if (entry.isDirectory()) return findTraceFiles(fullPath);
|
|
10
|
+
return entry.name.endsWith(".nft.json") ? [fullPath] : [];
|
|
11
|
+
}))).flat();
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The server reads the dictionaries from a path built at runtime, which Next's
|
|
15
|
+
* file tracing cannot see, so standalone and Vercel builds would leave them out.
|
|
16
|
+
*/
|
|
17
|
+
async function addDictionariesToTraces(distDir, locales) {
|
|
18
|
+
const dictionaries = (await Promise.all(locales.map(async (locale) => {
|
|
19
|
+
const file = path.join(distDir, `${locale}.json`);
|
|
20
|
+
return (await fs.stat(file).catch(() => null))?.isFile() ? file : null;
|
|
21
|
+
}))).filter((file) => file !== null);
|
|
22
|
+
if (dictionaries.length === 0) return;
|
|
23
|
+
const traceFiles = await findTraceFiles(path.join(distDir, "server"));
|
|
24
|
+
await Promise.all(traceFiles.map(async (traceFile) => {
|
|
25
|
+
const trace = JSON.parse(await fs.readFile(traceFile, "utf8"));
|
|
26
|
+
if (!Array.isArray(trace.files)) return;
|
|
27
|
+
const files = new Set(trace.files);
|
|
28
|
+
for (const dictionary of dictionaries) files.add(path.relative(path.dirname(traceFile), dictionary).split(path.sep).join("/"));
|
|
29
|
+
trace.files = [...files];
|
|
30
|
+
await fs.writeFile(traceFile, JSON.stringify(trace));
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
export { addDictionariesToTraces };
|
|
36
|
+
//# sourceMappingURL=next-traces.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"next-traces.mjs","names":[],"sources":["../../src/plugin/next-traces.ts"],"sourcesContent":["import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nasync function findTraceFiles(dir: string): Promise<string[]> {\n const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);\n const nested = await Promise.all(\n entries.map((entry) => {\n const fullPath = path.join(dir, entry.name);\n if (entry.isDirectory()) return findTraceFiles(fullPath);\n return entry.name.endsWith(\".nft.json\") ? [fullPath] : [];\n }),\n );\n return nested.flat();\n}\n\n/**\n * The server reads the dictionaries from a path built at runtime, which Next's\n * file tracing cannot see, so standalone and Vercel builds would leave them out.\n */\nexport async function addDictionariesToTraces(\n distDir: string,\n locales: string[],\n): Promise<void> {\n const written = await Promise.all(\n locales.map(async (locale) => {\n const file = path.join(distDir, `${locale}.json`);\n return (await fs.stat(file).catch(() => null))?.isFile() ? file : null;\n }),\n );\n const dictionaries = written.filter((file): file is string => file !== null);\n if (dictionaries.length === 0) return;\n const traceFiles = await findTraceFiles(path.join(distDir, \"server\"));\n\n await Promise.all(\n traceFiles.map(async (traceFile) => {\n const trace = JSON.parse(await fs.readFile(traceFile, \"utf8\"));\n if (!Array.isArray(trace.files)) return;\n const files = new Set<string>(trace.files);\n for (const dictionary of dictionaries) {\n files.add(path.relative(path.dirname(traceFile), diction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AAU,WAAW,KAAK,UAAU,MAAM,CAAC;GACpD,CACH"}
|
package/build/plugin/next.cjs
CHANGED
|
@@ -1,18 +1,26 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
1
2
|
const require_logger = require('../utils/logger.cjs');
|
|
2
3
|
const require_config_factory = require('../utils/config-factory.cjs');
|
|
3
4
|
const require_translation_service = require('../translators/translation-service.cjs');
|
|
4
5
|
const require_manager = require('../metadata/manager.cjs');
|
|
5
6
|
const require_translation_server = require('../translation-server/translation-server.cjs');
|
|
6
7
|
const require_build_translator = require('./build-translator.cjs');
|
|
8
|
+
const require_next_traces = require('./next-traces.cjs');
|
|
7
9
|
const require_cleanup = require('./cleanup.cjs');
|
|
8
10
|
const require_use_i18n = require('./transform/use-i18n.cjs');
|
|
11
|
+
const require_package_version = require('../utils/package-version.cjs');
|
|
12
|
+
let node_fs_promises = require("node:fs/promises");
|
|
13
|
+
node_fs_promises = require_rolldown_runtime.__toESM(node_fs_promises);
|
|
14
|
+
let node_path = require("node:path");
|
|
15
|
+
node_path = require_rolldown_runtime.__toESM(node_path);
|
|
9
16
|
|
|
10
17
|
//#region src/plugin/next.ts
|
|
11
18
|
function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
12
19
|
const common = {
|
|
13
20
|
sourceRoot: weglotConfig.sourceRoot,
|
|
14
21
|
weglotDir: weglotConfig.weglotDir,
|
|
15
|
-
sourceLocale: weglotConfig.sourceLocale
|
|
22
|
+
sourceLocale: weglotConfig.sourceLocale,
|
|
23
|
+
version: require_package_version.packageVersion()
|
|
16
24
|
};
|
|
17
25
|
const compilerLoader = {
|
|
18
26
|
loader: "@weglot/translate-react/next-compiler-loader",
|
|
@@ -132,10 +140,22 @@ function mergeTurbopackRules(existingRules, newRules) {
|
|
|
132
140
|
function isMainRunner() {
|
|
133
141
|
return !process.env.NEXT_PRIVATE_BUILD_WORKER && !process.env.IS_NEXT_WORKER && !process.env.NEXT_PRIVATE_WORKER;
|
|
134
142
|
}
|
|
143
|
+
async function failOnLostMetadata(metadataFilePath, lastBuildFile) {
|
|
144
|
+
if (Object.keys(await require_manager.loadMetadata(metadataFilePath, true)).length > 0) return;
|
|
145
|
+
const last = await node_fs_promises.default.readFile(lastBuildFile, "utf8").then((content) => JSON.parse(content).entries).catch(() => 0);
|
|
146
|
+
if (last > 0) throw new Error(`No translatable text was found, but the previous build had ${last} entries: the bundler served the files from its cache without the Weglot metadata. Delete ${node_path.default.relative(process.cwd(), node_path.default.dirname(node_path.default.dirname(lastBuildFile)))} and build again.`);
|
|
147
|
+
}
|
|
148
|
+
async function writeLastBuild(metadataFilePath, lastBuildFile) {
|
|
149
|
+
const entries = Object.keys(await require_manager.loadMetadata(metadataFilePath, true)).length;
|
|
150
|
+
await node_fs_promises.default.mkdir(node_path.default.dirname(lastBuildFile), { recursive: true });
|
|
151
|
+
await node_fs_promises.default.writeFile(lastBuildFile, JSON.stringify({ entries }));
|
|
152
|
+
}
|
|
135
153
|
async function withWeglot(nextConfig = {}, weglotOptions) {
|
|
136
154
|
const weglotConfig = require_config_factory.createWeglotConfig(weglotOptions);
|
|
137
155
|
await require_config_factory.resolveProjectLanguages(weglotConfig);
|
|
138
|
-
|
|
156
|
+
const distDir = node_path.default.resolve(nextConfig.distDir ?? ".next");
|
|
157
|
+
if (weglotConfig.environment !== "development") weglotConfig.metadataDir = node_path.default.join(distDir, "cache", "weglot", "metadata-build");
|
|
158
|
+
const metadataFilePath = require_manager.getMetadataPath(weglotConfig);
|
|
139
159
|
const isDev = weglotConfig.environment === "development";
|
|
140
160
|
require_logger.logger.debug(`Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
|
|
141
161
|
if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) if (weglotConfig.dev.translationServerUrl) {
|
|
@@ -158,11 +178,6 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
|
|
|
158
178
|
} });
|
|
159
179
|
}
|
|
160
180
|
const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;
|
|
161
|
-
if (isMainRunner()) {
|
|
162
|
-
const environment = weglotConfig.environment;
|
|
163
|
-
require_manager.cleanupMetadataForEnvironment(metadataFilePath, environment);
|
|
164
|
-
require_cleanup.registerCleanupOnCurrentProcess({ cleanup: () => require_manager.cleanupMetadataForEnvironment(metadataFilePath, environment) });
|
|
165
|
-
}
|
|
166
181
|
const existingTurbopackConfig = getTurbopackConfig(nextConfig);
|
|
167
182
|
let mergedRules = mergeTurbopackRules(existingTurbopackConfig.rules ?? {}, Object.values(loaders({
|
|
168
183
|
weglotConfig,
|
|
@@ -184,18 +199,23 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
|
|
|
184
199
|
resolveAlias: mergedResolveAlias
|
|
185
200
|
}
|
|
186
201
|
} };
|
|
187
|
-
const runAfterProductionCompile = async ({ distDir, projectDir }) => {
|
|
202
|
+
const runAfterProductionCompile = async ({ distDir: distDir$1, projectDir }) => {
|
|
188
203
|
if (typeof nextConfig.compiler?.runAfterProductionCompile === "function") await nextConfig.compiler.runAfterProductionCompile({
|
|
189
|
-
distDir,
|
|
204
|
+
distDir: distDir$1,
|
|
190
205
|
projectDir
|
|
191
206
|
});
|
|
192
207
|
require_logger.logger.info("Running post-build translation generation...");
|
|
208
|
+
const lastBuildFile = node_path.default.join(distDir$1, "cache", "weglot", "last-build.json");
|
|
193
209
|
try {
|
|
210
|
+
await require_manager.pruneMetadata(metadataFilePath);
|
|
211
|
+
await failOnLostMetadata(metadataFilePath, lastBuildFile);
|
|
194
212
|
await require_build_translator.processBuildTranslations({
|
|
195
213
|
config: weglotConfig,
|
|
196
|
-
publicOutputPath: distDir,
|
|
214
|
+
publicOutputPath: distDir$1,
|
|
197
215
|
metadataFilePath
|
|
198
216
|
});
|
|
217
|
+
await require_next_traces.addDictionariesToTraces(distDir$1, weglotConfig.targetLocales);
|
|
218
|
+
await writeLastBuild(metadataFilePath, lastBuildFile);
|
|
199
219
|
} catch (error) {
|
|
200
220
|
require_logger.logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
|
|
201
221
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAuBY,uBAAA,GAA0B;iBAiNhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAuBY,uBAAA,GAA0B;iBAiNhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
|