@weglot/translate-react 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -4
- package/build/plugin/build-translator.cjs +4 -1
- package/build/plugin/build-translator.mjs +4 -1
- package/build/plugin/build-translator.mjs.map +1 -1
- package/build/plugin/next.cjs +1 -0
- package/build/plugin/next.d.cts.map +1 -1
- package/build/plugin/next.d.mts.map +1 -1
- package/build/plugin/next.mjs +1 -0
- package/build/plugin/next.mjs.map +1 -1
- package/build/plugin/vite.cjs +1 -1
- package/build/plugin/vite.mjs +1 -1
- package/build/plugin/vite.mjs.map +1 -1
- package/build/plugin/webpack.cjs +1 -1
- package/build/plugin/webpack.mjs +1 -1
- package/build/plugin/webpack.mjs.map +1 -1
- package/build/react/server/ServerWeglotProvider.d.cts +2 -2
- package/build/react/shared/WeglotProvider.d.cts +2 -2
- package/build/runtime/translate-dynamic.cjs +5 -3
- package/build/runtime/translate-dynamic.d.cts.map +1 -1
- package/build/runtime/translate-dynamic.d.mts.map +1 -1
- package/build/runtime/translate-dynamic.mjs +6 -4
- package/build/runtime/translate-dynamic.mjs.map +1 -1
- package/build/translators/translation-service.cjs +4 -2
- package/build/translators/translation-service.mjs +4 -2
- package/build/translators/translation-service.mjs.map +1 -1
- package/build/translators/weglot/api-client.cjs +75 -23
- package/build/translators/weglot/api-client.mjs +75 -24
- package/build/translators/weglot/api-client.mjs.map +1 -1
- package/build/translators/weglot/engine.cjs +2 -5
- package/build/translators/weglot/engine.mjs +2 -5
- package/build/translators/weglot/engine.mjs.map +1 -1
- package/build/translators/weglot/translator.cjs +31 -25
- package/build/translators/weglot/translator.mjs +31 -25
- package/build/translators/weglot/translator.mjs.map +1 -1
- package/build/types.d.cts +13 -3
- package/build/types.d.cts.map +1 -1
- package/build/types.d.mts +13 -3
- package/build/types.d.mts.map +1 -1
- package/build/utils/config-factory.cjs +18 -4
- package/build/utils/config-factory.mjs +19 -5
- package/build/utils/config-factory.mjs.map +1 -1
- package/build/virtual/code-generator.cjs +2 -0
- package/build/virtual/code-generator.mjs +2 -0
- package/build/virtual/code-generator.mjs.map +1 -1
- package/build/virtual/config.cjs +3 -0
- package/build/virtual/config.d.cts +3 -1
- package/build/virtual/config.d.cts.map +1 -1
- package/build/virtual/config.d.mts +3 -1
- package/build/virtual/config.d.mts.map +1 -1
- package/build/virtual/config.mjs +3 -1
- package/build/virtual/config.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ npm install @weglot/translate-react@next
|
|
|
18
18
|
Set your project key in `.env`:
|
|
19
19
|
|
|
20
20
|
```bash
|
|
21
|
-
WEGLOT_API_KEY=
|
|
21
|
+
WEGLOT_API_KEY=your_weglot_project_key
|
|
22
22
|
```
|
|
23
23
|
|
|
24
24
|
### Vite
|
|
@@ -87,6 +87,7 @@ Exclude an element with `translate="no"` or `data-weglot-skip`.
|
|
|
87
87
|
| `sourceRoot` | `string` | `"src"` | Root directory of the source code |
|
|
88
88
|
| `useDirective` | `boolean` | `false` | Only transform files containing `'use i18n'` |
|
|
89
89
|
| `buildMode` | `"translate" \| "cache-only"` | `"translate"` | See below |
|
|
90
|
+
| `translationTimeout` | `number` | `300` in a build, `10` in dev | Seconds to wait for translations Weglot is still generating; `WEGLOT_TRANSLATION_TIMEOUT` env var |
|
|
90
91
|
| `dev.translationServerStartPort` | `number` | `60000` | Dev translation server port |
|
|
91
92
|
| `localePersistence` | cookie config | `{ type: "cookie", config: { name: "locale", maxAge: 31536000 } }` | Locale cookie |
|
|
92
93
|
| `translatableAttributes` | `Record<string, string[]>` | `{}` | Per-element attribute overrides, see below |
|
|
@@ -125,6 +126,12 @@ Languages are not configured here: they come from your Weglot project.
|
|
|
125
126
|
- `cache-only`: no network calls; the build fails if the local cache is
|
|
126
127
|
incomplete. Override per build with `WEGLOT_BUILD_MODE=cache-only`.
|
|
127
128
|
|
|
129
|
+
Weglot generates translations with an LLM, so new strings can take a moment:
|
|
130
|
+
the build waits for them up to `translationTimeout`. If some are still not
|
|
131
|
+
ready, the build fails, keeping the ones it received in the local cache, so
|
|
132
|
+
building again — without the `.next` cache — picks up where it stopped. In dev,
|
|
133
|
+
strings not ready in time show in the source language until the next reload.
|
|
134
|
+
|
|
128
135
|
## React API
|
|
129
136
|
|
|
130
137
|
```tsx
|
|
@@ -163,9 +170,11 @@ fragment the way the Weglot proxy splits a page, so inline markup survives.
|
|
|
163
170
|
|
|
164
171
|
Calls made in the same render are batched into one request, and all of them
|
|
165
172
|
return the source text if the API takes longer than 500ms — a slow call never
|
|
166
|
-
holds up a page.
|
|
167
|
-
|
|
168
|
-
|
|
173
|
+
holds up a page. Text Weglot has not translated yet also comes back as source
|
|
174
|
+
the first time; later requests get the translation once it is generated. Pass
|
|
175
|
+
`{ timeoutMs }` to change that, or `{ locale }` to override the locale for one
|
|
176
|
+
call. `configureDynamicTranslation({ apiKey })` sets the key when it does not
|
|
177
|
+
come from the environment.
|
|
169
178
|
|
|
170
179
|
## Development (this repo)
|
|
171
180
|
|
|
@@ -199,7 +199,10 @@ function formatTranslationErrors(errors) {
|
|
|
199
199
|
msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join("\n");
|
|
200
200
|
msg += "\n\n";
|
|
201
201
|
msg += ` 💡 Translation errors must be resolved in "translate" mode.\n`;
|
|
202
|
-
msg += `
|
|
202
|
+
msg += ` If Weglot was still generating translations, build again without the\n`;
|
|
203
|
+
msg += ` .next cache: the ones received are kept. Raise WEGLOT_TRANSLATION_TIMEOUT\n`;
|
|
204
|
+
msg += ` to wait longer.\n`;
|
|
205
|
+
msg += ` Otherwise, check translation server logs for details.`;
|
|
203
206
|
return msg;
|
|
204
207
|
}
|
|
205
208
|
|
|
@@ -196,7 +196,10 @@ function formatTranslationErrors(errors) {
|
|
|
196
196
|
msg += errors.map((err) => ` - ${err.locale}: ${err.error}`).join("\n");
|
|
197
197
|
msg += "\n\n";
|
|
198
198
|
msg += ` 💡 Translation errors must be resolved in "translate" mode.\n`;
|
|
199
|
-
msg += `
|
|
199
|
+
msg += ` If Weglot was still generating translations, build again without the\n`;
|
|
200
|
+
msg += ` .next cache: the ones received are kept. Raise WEGLOT_TRANSLATION_TIMEOUT\n`;
|
|
201
|
+
msg += ` to wait longer.\n`;
|
|
202
|
+
msg += ` Otherwise, check translation server logs for details.`;
|
|
200
203
|
return msg;
|
|
201
204
|
}
|
|
202
205
|
|
|
@@ -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 += ` 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,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,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"}
|
|
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.\\n`;\n msg += ` Otherwise, check translation server logs for details.`;\n\n return msg;\n}\n"],"mappings":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AAkB,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"}
|
package/build/plugin/next.cjs
CHANGED
|
@@ -29,6 +29,7 @@ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
|
29
29
|
...common,
|
|
30
30
|
apiLocales: weglotConfig.apiLocales,
|
|
31
31
|
translationEngine: weglotConfig.translationEngine,
|
|
32
|
+
apiBaseUrl: weglotConfig.apiBaseUrl,
|
|
32
33
|
dev: Object.fromEntries(Object.entries({
|
|
33
34
|
translationServerUrl,
|
|
34
35
|
...weglotConfig.dev
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAmBY,uBAAA,GAA0B;
|
|
1
|
+
{"version":3,"file":"next.d.cts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAmBY,uBAAA,GAA0B;iBA2LhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAmBY,uBAAA,GAA0B;
|
|
1
|
+
{"version":3,"file":"next.d.mts","names":[],"sources":["../../src/plugin/next.ts"],"sourcesContent":[],"mappings":";;;;KAmBY,uBAAA,GAA0B;iBA2LhB,UAAA,aACR,uCACG,0BACd,QAAQ"}
|
package/build/plugin/next.mjs
CHANGED
|
@@ -30,6 +30,7 @@ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
|
|
|
30
30
|
...common,
|
|
31
31
|
apiLocales: weglotConfig.apiLocales,
|
|
32
32
|
translationEngine: weglotConfig.translationEngine,
|
|
33
|
+
apiBaseUrl: weglotConfig.apiBaseUrl,
|
|
33
34
|
dev: Object.fromEntries(Object.entries({
|
|
34
35
|
translationServerUrl,
|
|
35
36
|
...weglotConfig.dev
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport {\n createWeglotConfig,\n resolveProjectLanguages,\n} from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { WeglotConfig, PartialWeglotConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { cleanupMetadataForEnvironment, getMetadataPath } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { TranslationService } from \"../translators\";\n\nexport type WeglotNextPluginOptions = PartialWeglotConfig;\n\ntype RuleKey = \"compiler\" | \"config\" | \"localeServer\" | \"localeClient\";\n\nfunction loaders({\n weglotConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n weglotConfig: WeglotConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: weglotConfig.sourceRoot,\n weglotDir: weglotConfig.weglotDir,\n sourceLocale: weglotConfig.sourceLocale,\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@weglot/translate-react/next-compiler-loader\",\n options: {\n ...common,\n useDirective: weglotConfig.useDirective,\n translatableAttributes: weglotConfig.translatableAttributes,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@weglot/translate-react/next-config-loader\",\n options: {\n ...common,\n // The runtime reads these to address the API without a settings call.\n apiLocales: weglotConfig.apiLocales,\n translationEngine: weglotConfig.translationEngine,\n // Turbopack rejects undefined options, left by an absent server URL.\n dev: Object.fromEntries(\n Object.entries({ translationServerUrl, ...weglotConfig.dev }).filter(\n ([, value]) => value !== undefined,\n ),\n ),\n },\n };\n const localeServerLoader = {\n loader: \"@weglot/translate-react/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@weglot/translate-react/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: {\n content: weglotConfig.useDirective ? useI18nRegex : undefined,\n },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n // Every environment, not just dev: it also carries the locale map and engine,\n // whose placeholders would otherwise reach the browser.\n config: {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n },\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nexport async function withWeglot(\n nextConfig: NextConfig = {},\n weglotOptions: WeglotNextPluginOptions,\n): Promise<NextConfig> {\n const weglotConfig = createWeglotConfig(weglotOptions);\n await resolveProjectLanguages(weglotConfig);\n let metadataFilePath = getMetadataPath(weglotConfig);\n const isDev = weglotConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) {\n if (weglotConfig.dev.translationServerUrl) {\n logger.info(`Using existing translation server URL (${weglotConfig.dev.translationServerUrl}) from config`);\n process.env.WEGLOT_TRANSLATION_SERVER_URL =\n weglotConfig.dev.translationServerUrl;\n } else {\n const translationServer = await startOrGetTranslationServer({\n translationService: new TranslationService(weglotConfig, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(\n `Translation server started successfully on port: ${port}`,\n );\n },\n config: weglotConfig,\n });\n process.env.WEGLOT_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n }\n\n const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;\n\n if (isMainRunner()) {\n const environment = weglotConfig.environment;\n cleanupMetadataForEnvironment(metadataFilePath, environment);\n\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment),\n });\n }\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n\n try {\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\n \"Translation generation failed:\",\n error instanceof Error ? error.message : error,\n );\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const weglotRules = Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...weglotRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;;AAuBA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,aAAa;EACzB,WAAW,aAAa;EACxB,cAAc,aAAa;EAC5B;CAGD,MAAM,iBAAiB;EACrB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,cAAc,aAAa;GAC3B,wBAAwB,aAAa;GACrC;GACD;EACF;CAED,MAAM,eAAe;EACnB,QAAQ;EACR,SAAS;GACP,GAAG;GAEH,YAAY,aAAa;GACzB,mBAAmB,aAAa;GAEhC,KAAK,OAAO,YACV,OAAO,QAAQ;IAAE;IAAsB,GAAG,aAAa;IAAK,CAAC,CAAC,QAC3D,GAAG,WAAW,UAAU,OAC1B,CACF;GACF;EACF;CACD,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;CAED,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;AAED,QAAO;EACL,UAAU;GACR,WAAW;IACT,SAAS;IACT,QAAQ;KACN,WAAW,EACT,SAAS,aAAa,eAAe,eAAe,QACrD;KACD,SAAS,CAAC,eAAe;KAC1B;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,SAAS;IACT,KAAK,CAAC,eAAe;IACtB;GACF;EAID,QA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AC5B,OAAO;GACP,cAAc;GACf;EACF,EACF;CAGH,MAAM,4BAA4B,OAAO,EACvC,SACA,iBAII;AACJ,MAAI,OAAO,WAAW,UAAU,8BAA8B,WAC5D,OAAM,WAAW,SAAS,0BAA0B;GAClD;GACA;GACD,CAAC;AAGJ,SAAO,KAAK,+CAA+C;AAE3D,MAAI;AACF,SAAM,yBAAyB;IAC7B,QAAQ;IACR,kBAAkB;IAClB;IACD,CAAC;WACK,OAAO;AACd,UAAO,MACL,kCACA,iBAAiB,QAAQ,MAAM,UAAU,MAC1C;AACD,SAAM;;;CAIV,MAAMC,WACJ,QACA,YACG;EAEH,IAAI,iBAAiB;AACrB,MAAI,OAAO,WAAW,YAAY,WAChC,kBAAiB,WAAW,QAAQ,QAAQ,QAAQ;EAGtD,MAAM,cAAc,OAAO,OACzB,QAAQ;GAAE;GAAc;GAAkB;GAAsB,CAAC,CAClE,CACE,KAAK,UAAU,MAAM,QAAQ,CAC7B,OAAO,QAAQ;AAIlB,iBAAe,OAAO,MAAM,QAAQ,GAAG,YAAY;AAEnD,SAAO;;AAGT,QAAO;EACL,GAAG;EACH,GAAG;EACH,UAAU;GACR,GAAG,WAAW;GACd;GACD;EACD;EACD"}
|
|
1
|
+
{"version":3,"file":"next.mjs","names":["turbopackConfig: Partial<NextConfig>","webpack: NextJsWebpackConfig"],"sources":["../../src/plugin/next.ts"],"sourcesContent":["import type { NextConfig } from \"next\";\nimport type {\n NextJsWebpackConfig,\n TurbopackOptions,\n WebpackConfigContext,\n} from \"next/dist/server/config-shared\";\nimport {\n createWeglotConfig,\n resolveProjectLanguages,\n} from \"../utils/config-factory\";\nimport { logger } from \"../utils/logger\";\nimport type { WeglotConfig, PartialWeglotConfig } from \"../types\";\nimport { processBuildTranslations } from \"./build-translator\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { cleanupMetadataForEnvironment, getMetadataPath } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { TranslationService } from \"../translators\";\n\nexport type WeglotNextPluginOptions = PartialWeglotConfig;\n\ntype RuleKey = \"compiler\" | \"config\" | \"localeServer\" | \"localeClient\";\n\nfunction loaders({\n weglotConfig,\n metadataFilePath,\n translationServerUrl,\n}: {\n weglotConfig: WeglotConfig;\n metadataFilePath: string;\n translationServerUrl?: string;\n}): Record<RuleKey, { turbopack?: any; webpack?: any }> {\n const common = {\n sourceRoot: weglotConfig.sourceRoot,\n weglotDir: weglotConfig.weglotDir,\n sourceLocale: weglotConfig.sourceLocale,\n };\n\n // TODO (AleksandrSl 14/12/2025): Type options.\n const compilerLoader = {\n loader: \"@weglot/translate-react/next-compiler-loader\",\n options: {\n ...common,\n useDirective: weglotConfig.useDirective,\n translatableAttributes: weglotConfig.translatableAttributes,\n metadataFilePath,\n },\n };\n\n const configLoader = {\n loader: \"@weglot/translate-react/next-config-loader\",\n options: {\n ...common,\n // The runtime reads these to address the API without a settings call.\n apiLocales: weglotConfig.apiLocales,\n translationEngine: weglotConfig.translationEngine,\n apiBaseUrl: weglotConfig.apiBaseUrl,\n // Turbopack rejects undefined options, left by an absent server URL.\n dev: Object.fromEntries(\n Object.entries({ translationServerUrl, ...weglotConfig.dev }).filter(\n ([, value]) => value !== undefined,\n ),\n ),\n },\n };\n const localeServerLoader = {\n loader: \"@weglot/translate-react/next-locale-server-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n const localeClientLoader = {\n loader: \"@weglot/translate-react/next-locale-client-loader\",\n options: {\n ...common,\n localePersistence: weglotConfig.localePersistence,\n },\n };\n\n return {\n compiler: {\n turbopack: {\n pattern: \"*.{tsx,jsx}\",\n config: {\n condition: {\n content: weglotConfig.useDirective ? useI18nRegex : undefined,\n },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n // Every environment, not just dev: it also carries the locale map and engine,\n // whose placeholders would otherwise reach the browser.\n config: {\n turbopack: {\n pattern: \"**/virtual/config.mjs\",\n config: {\n loaders: [configLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/config\\.mjs$/i,\n use: [configLoader],\n },\n },\n\n localeServer: {\n turbopack: {\n pattern: \"**/virtual/locale/server.mjs\",\n config: {\n loaders: [localeServerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]server\\.mjs$/i,\n use: [localeServerLoader],\n },\n },\n\n localeClient: {\n turbopack: {\n pattern: \"**/virtual/locale/client.mjs\",\n config: {\n loaders: [localeClientLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /virtual\\/locale[\\\\/]client\\.mjs$/i,\n use: [localeClientLoader],\n },\n },\n };\n}\n\n/**\n * Check if Next.js supports stable turbopack config (Next.js 16+)\n */\nfunction hasStableTurboConfig(): boolean {\n try {\n const nextPackage = require(\"next/package.json\");\n const majorVersion = parseInt(nextPackage.version.split(\".\")[0], 10);\n return majorVersion >= 16;\n } catch {\n return false;\n }\n}\n\nfunction getTurbopackConfig(userConfig: NextConfig): TurbopackOptions {\n return (\n (hasStableTurboConfig()\n ? userConfig?.turbopack\n : // @ts-expect-error - experimental.turbo for Next.js <16\n userConfig?.experimental?.turbo) || {}\n );\n}\n\n/**\n * Merge Turbopack rules without mutating original\n */\nfunction mergeTurbopackRules(\n existingRules: Record<string, any>,\n newRules: ({ pattern: string; config: any } | undefined)[],\n): Record<string, any> {\n const mergedRules = { ...existingRules };\n\n for (const newRule of newRules) {\n if (!newRule) continue;\n const { pattern, config } = newRule;\n\n if (mergedRules[pattern]) {\n if (Array.isArray(mergedRules[pattern])) {\n mergedRules[pattern] = [...mergedRules[pattern], config];\n } else {\n mergedRules[pattern] = [mergedRules[pattern], config];\n }\n } else {\n mergedRules[pattern] = config;\n }\n }\n\n return mergedRules;\n}\n\n// Next read config several times. Once in the main runner,\n// and ~ twice in the build workers which cannot get the config otherwise, because it's not serializable.\n// Workers start in separate processed by get most of the env from the main loader\nfunction isMainRunner() {\n return (\n !process.env.NEXT_PRIVATE_BUILD_WORKER &&\n !process.env.IS_NEXT_WORKER &&\n !process.env.NEXT_PRIVATE_WORKER\n );\n}\n\nexport async function withWeglot(\n nextConfig: NextConfig = {},\n weglotOptions: WeglotNextPluginOptions,\n): Promise<NextConfig> {\n const weglotConfig = createWeglotConfig(weglotOptions);\n await resolveProjectLanguages(weglotConfig);\n let metadataFilePath = getMetadataPath(weglotConfig);\n const isDev = weglotConfig.environment === \"development\";\n\n logger.debug(\n `Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`,\n );\n\n // Try to start up the translation server once.\n // We have two barriers, a simple one here and a more complex one inside the startTranslationServer which doesn't start the server if it can find one running.\n // We do not use isMainRunner here, because we need to start the server as early as possible, so the loaders get the translation server url. The main runner in dev mode runs after a dev server process is started.\n if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) {\n if (weglotConfig.dev.translationServerUrl) {\n logger.info(`Using existing translation server URL (${weglotConfig.dev.translationServerUrl}) from config`);\n process.env.WEGLOT_TRANSLATION_SERVER_URL =\n weglotConfig.dev.translationServerUrl;\n } else {\n const translationServer = await startOrGetTranslationServer({\n translationService: new TranslationService(weglotConfig, logger),\n onError: (err) => {\n logger.error(\"Translation server error:\", err);\n },\n onReady: (port) => {\n logger.info(\n `Translation server started successfully on port: ${port}`,\n );\n },\n config: weglotConfig,\n });\n process.env.WEGLOT_TRANSLATION_SERVER_URL = translationServer.url;\n if (translationServer.server) {\n // We start the server in the same process, so we should be fine without any sync cleanup. Server should be killed with the process.\n registerCleanupOnCurrentProcess({\n asyncCleanup: async () => {\n await translationServer.server.stop();\n },\n });\n }\n }\n }\n\n const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;\n\n if (isMainRunner()) {\n const environment = weglotConfig.environment;\n cleanupMetadataForEnvironment(metadataFilePath, environment);\n\n registerCleanupOnCurrentProcess({\n cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment),\n });\n }\n\n const existingTurbopackConfig = getTurbopackConfig(nextConfig);\n let mergedRules = mergeTurbopackRules(\n existingTurbopackConfig.rules ?? {},\n Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n ).map((rules) => rules.turbopack),\n );\n\n const existingResolveAlias = existingTurbopackConfig.resolveAlias;\n const mergedResolveAlias = {\n ...existingResolveAlias,\n };\n\n let turbopackConfig: Partial<NextConfig>;\n if (hasStableTurboConfig()) {\n turbopackConfig = {\n turbopack: {\n ...nextConfig.turbopack, // Preserve existing turbopack options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n };\n } else {\n turbopackConfig = {\n experimental: {\n ...nextConfig.experimental, // Preserve ALL experimental options\n // @ts-expect-error - turbo for Next.js <16\n turbo: {\n // @ts-expect-error - turbo for Next.js <16\n ...nextConfig.experimental?.turbo, // Preserve existing turbo options\n rules: mergedRules,\n resolveAlias: mergedResolveAlias,\n },\n },\n };\n }\n\n const runAfterProductionCompile = async ({\n distDir,\n projectDir,\n }: {\n distDir: string;\n projectDir: string;\n }) => {\n if (typeof nextConfig.compiler?.runAfterProductionCompile === \"function\") {\n await nextConfig.compiler.runAfterProductionCompile({\n distDir,\n projectDir,\n });\n }\n\n logger.info(\"Running post-build translation generation...\");\n\n try {\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n } catch (error) {\n logger.error(\n \"Translation generation failed:\",\n error instanceof Error ? error.message : error,\n );\n throw error;\n }\n };\n\n const webpack: NextJsWebpackConfig = (\n config: any,\n options: WebpackConfigContext,\n ) => {\n // Apply user's webpack config first if it exists\n let modifiedConfig = config;\n if (typeof nextConfig.webpack === \"function\") {\n modifiedConfig = nextConfig.webpack(config, options);\n }\n\n const weglotRules = Object.values(\n loaders({ weglotConfig, metadataFilePath, translationServerUrl }),\n )\n .map((rules) => rules.webpack)\n .filter(Boolean);\n\n // I tried using plugin from unplugin, but with all the loaders stuff it works poorly.\n // Failing with weird errors which appear on the later compilations, probably something with the cache and virtual modules\n modifiedConfig.module.rules.unshift(...weglotRules);\n\n return modifiedConfig;\n };\n\n return {\n ...nextConfig,\n ...turbopackConfig,\n compiler: {\n ...nextConfig.compiler,\n runAfterProductionCompile,\n },\n webpack,\n };\n}\n"],"mappings":";;;;;;;;;;;AAuBA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,aAAa;EACzB,WAAW,aAAa;EACxB,cAAc,aAAa;EAC5B;CAGD,MAAM,iBAAiB;EACrB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,cAAc,aAAa;GAC3B,wBAAwB,aAAa;GACrC;GACD;EACF;CAED,MAAM,eAAe;EACnB,QAAQ;EACR,SAAS;GACP,GAAG;GAEH,YAAY,aAAa;GACzB,mBAAmB,aAAa;GAChC,YAAY,aAAa;GAEzB,KAAK,OAAO,YACV,OAAO,QAAQ;IAAE;IAAsB,GAAG,aAAa;IAAK,CAAC,CAAC,QAC3D,GAAG,WAAW,UAAU,OAC1B,CACF;GACF;EACF;CACD,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;CAED,MAAM,qBAAqB;EACzB,QAAQ;EACR,SAAS;GACP,GAAG;GACH,mBAAmB,aAAa;GACjC;EACF;AAED,QAAO;EACL,UAAU;GACR,WAAW;IACT,SAAS;IACT,QAAQ;KACN,WAAW,EACT,SAAS,aAAa,eAAe,eAAe,QACrD;KACD,SAAS,CAAC,eAAe;KAC1B;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,SAAS;IACT,KAAK,CAAC,eAAe;IACtB;GACF;EAID,QAAQ;GACN,WAAW;IACT,SAAS;IACT,QAAQ,EACN,SAAS,CAAC,aAAa,EACxB;IACF;GACD,SAAS;IACP,SAAS;IACT,MAAM;IACN,KAAK,C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B,WAC5D,OAAM,WAAW,SAAS,0BAA0B;GAClD;GACA;GACD,CAAC;AAGJ,SAAO,KAAK,+CAA+C;AAE3D,MAAI;AACF,SAAM,yBAAyB;IAC7B,QAAQ;IACR,kBAAkB;IAClB;IACD,CAAC;WACK,OAAO;AACd,UAAO,MACL,kCACA,iBAAiB,QAAQ,MAAM,UAAU,MAC1C;AACD,SAAM;;;CAIV,MAAMC,WACJ,QACA,YACG;EAEH,IAAI,iBAAiB;AACrB,MAAI,OAAO,WAAW,YAAY,WAChC,kBAAiB,WAAW,QAAQ,QAAQ,QAAQ;EAGtD,MAAM,cAAc,OAAO,OACzB,QAAQ;GAAE;GAAc;GAAkB;GAAsB,CAAC,CAClE,CACE,KAAK,UAAU,MAAM,QAAQ,CAC7B,OAAO,QAAQ;AAIlB,iBAAe,OAAO,MAAM,QAAQ,GAAG,YAAY;AAEnD,SAAO;;AAGT,QAAO;EACL,GAAG;EACH,GAAG;EACH,UAAU;GACR,GAAG,WAAW;GACd;GACD;EACD;EACD"}
|
package/build/plugin/vite.cjs
CHANGED
package/build/plugin/vite.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.mjs","names":[],"sources":["../../src/plugin/vite.ts"],"sourcesContent":["/**\n * Vite plugin for @weglot/translate-react\n *\n * Usage:\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { weglotPlugin } from '@weglot/translate-react/vite';\n *\n * export default defineConfig({\n * plugins: [\n * weglotPlugin({\n * apiKey: '
|
|
1
|
+
{"version":3,"file":"vite.mjs","names":[],"sources":["../../src/plugin/vite.ts"],"sourcesContent":["/**\n * Vite plugin for @weglot/translate-react\n *\n * Usage:\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from 'vite';\n * import { weglotPlugin } from '@weglot/translate-react/vite';\n *\n * export default defineConfig({\n * plugins: [\n * weglotPlugin({\n * apiKey: 'your_weglot_project_key',\n * }),\n * ],\n * });\n * ```\n */\n\nimport { type WeglotPluginOptions, weglotUnplugin } from \"./unplugin\";\n\nexport function weglotPlugin(options: WeglotPluginOptions) {\n return weglotUnplugin.vite(options);\n}\n\nexport type { WeglotPluginOptions };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,aAAa,SAA8B;AACzD,QAAO,eAAe,KAAK,QAAQ"}
|
package/build/plugin/webpack.cjs
CHANGED
package/build/plugin/webpack.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.mjs","names":[],"sources":["../../src/plugin/webpack.ts"],"sourcesContent":["/**\n * Webpack plugin for @weglot/translate-react\n *\n * Usage:\n * ```js\n * // webpack.config.js\n * import { weglotPlugin } from '@weglot/translate-react/webpack';\n *\n * export default {\n * plugins: [\n * weglotPlugin({\n * apiKey: '
|
|
1
|
+
{"version":3,"file":"webpack.mjs","names":[],"sources":["../../src/plugin/webpack.ts"],"sourcesContent":["/**\n * Webpack plugin for @weglot/translate-react\n *\n * Usage:\n * ```js\n * // webpack.config.js\n * import { weglotPlugin } from '@weglot/translate-react/webpack';\n *\n * export default {\n * plugins: [\n * weglotPlugin({\n * apiKey: 'your_weglot_project_key',\n * }),\n * ],\n * };\n * ```\n */\n\nimport { weglotUnplugin, type WeglotPluginOptions } from \"./unplugin\";\n\nexport function weglotPlugin(options: WeglotPluginOptions) {\n return weglotUnplugin.webpack(options);\n}\n\nexport type { WeglotPluginOptions };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,aAAa,SAA8B;AACzD,QAAO,eAAe,QAAQ,QAAQ"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { WeglotProviderProps } from "../shared/WeglotProvider.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime1 from "react/jsx-runtime";
|
|
3
3
|
|
|
4
4
|
//#region src/react/server/ServerWeglotProvider.d.ts
|
|
5
5
|
declare function WeglotProvider({
|
|
6
6
|
initialLocale,
|
|
7
7
|
initialTranslations,
|
|
8
8
|
...rest
|
|
9
|
-
}: WeglotProviderProps): Promise<
|
|
9
|
+
}: WeglotProviderProps): Promise<react_jsx_runtime1.JSX.Element>;
|
|
10
10
|
//#endregion
|
|
11
11
|
export { WeglotProvider };
|
|
12
12
|
//# sourceMappingURL=ServerWeglotProvider.d.cts.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LocaleCode } from "../../locale.cjs";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react_jsx_runtime3 from "react/jsx-runtime";
|
|
3
3
|
import { PropsWithChildren } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/react/shared/WeglotProvider.d.ts
|
|
@@ -54,7 +54,7 @@ declare function WeglotProvider__Dev({
|
|
|
54
54
|
initialTranslations,
|
|
55
55
|
router,
|
|
56
56
|
children
|
|
57
|
-
}: WeglotProviderProps):
|
|
57
|
+
}: WeglotProviderProps): react_jsx_runtime3.JSX.Element;
|
|
58
58
|
//#endregion
|
|
59
59
|
export { WeglotProvider, WeglotProviderProps };
|
|
60
60
|
//# sourceMappingURL=WeglotProvider.d.cts.map
|
|
@@ -69,7 +69,7 @@ async function flush(key, locale, timeoutMs) {
|
|
|
69
69
|
queue.forEach((word) => word.resolve(word.text));
|
|
70
70
|
return;
|
|
71
71
|
}
|
|
72
|
-
const client = new require_api_client.WeglotApiClient(apiKey);
|
|
72
|
+
const client = new require_api_client.WeglotApiClient(apiKey, _weglot_translate_react_virtual_config.apiBaseUrl);
|
|
73
73
|
const chunks = [];
|
|
74
74
|
for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
|
|
75
75
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -86,11 +86,13 @@ async function flush(key, locale, timeoutMs) {
|
|
|
86
86
|
from: _weglot_translate_react_virtual_config.sourceLocale,
|
|
87
87
|
to: _weglot_translate_react_virtual_config.apiLocales[locale] ?? locale,
|
|
88
88
|
words: chunk.map((word) => word.text),
|
|
89
|
-
types: chunk.map((word) => word.type ?? require_definitions_generated.WORD_TYPE.TEXT)
|
|
89
|
+
types: chunk.map((word) => word.type ?? require_definitions_generated.WORD_TYPE.TEXT),
|
|
90
|
+
live: true
|
|
90
91
|
}), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
|
|
91
92
|
chunk.forEach((word, index) => {
|
|
92
93
|
const result = translated[index];
|
|
93
|
-
if (result ===
|
|
94
|
+
if (result === null) require_logger.logger.debug(`Weglot is still translating dynamic content for locale "${locale}".`);
|
|
95
|
+
else if (result === word.text) require_logger.logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
|
|
94
96
|
word.resolve(result ?? word.text);
|
|
95
97
|
});
|
|
96
98
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"translate-dynamic.d.cts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AA0DgB,UAvBC,yBAAA,CAuB0B;EAmJrB;EAwBA,MAAA,CAAA,EAhMX,UAgMuB;EAqBZ;;;UAhNL,wBAAA;;;;;;iBAgBD,2BAAA,OACR;;iBAkJc,QAAA,yBAEX,4BACR;;;;;iBAqBmB,YAAA,yBAEX,4BACR;;iBAkBmB,WAAA,4BAEX,4BACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"translate-dynamic.d.mts","names":[],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":[],"mappings":";;;;AA0DgB,UAvBC,yBAAA,CAuB0B;EAmJrB;EAwBA,MAAA,CAAA,EAhMX,UAgMuB;EAqBZ;;;UAhNL,wBAAA;;;;;;iBAgBD,2BAAA,OACR;;iBAkJc,QAAA,yBAEX,4BACR;;;;;iBAqBmB,YAAA,yBAEX,4BACR;;iBAkBmB,WAAA,4BAEX,4BACR"}
|
|
@@ -4,7 +4,7 @@ import { WORD_TYPE } from "../translators/weglot/definitions/definitions.generat
|
|
|
4
4
|
import { WeglotApiClient } from "../translators/weglot/api-client.mjs";
|
|
5
5
|
import { HtmlSegmenter } from "./html/segmenter.mjs";
|
|
6
6
|
import { cache } from "react";
|
|
7
|
-
import { apiLocales, sourceLocale, translationEngine } from "@weglot/translate-react/virtual/config";
|
|
7
|
+
import { apiBaseUrl, apiLocales, sourceLocale, translationEngine } from "@weglot/translate-react/virtual/config";
|
|
8
8
|
import { getServerLocale } from "@weglot/translate-react/virtual/locale/server";
|
|
9
9
|
|
|
10
10
|
//#region src/runtime/translate-dynamic.ts
|
|
@@ -68,7 +68,7 @@ async function flush(key, locale, timeoutMs) {
|
|
|
68
68
|
queue.forEach((word) => word.resolve(word.text));
|
|
69
69
|
return;
|
|
70
70
|
}
|
|
71
|
-
const client = new WeglotApiClient(apiKey);
|
|
71
|
+
const client = new WeglotApiClient(apiKey, apiBaseUrl);
|
|
72
72
|
const chunks = [];
|
|
73
73
|
for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));
|
|
74
74
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -85,11 +85,13 @@ async function flush(key, locale, timeoutMs) {
|
|
|
85
85
|
from: sourceLocale,
|
|
86
86
|
to: apiLocales[locale] ?? locale,
|
|
87
87
|
words: chunk.map((word) => word.text),
|
|
88
|
-
types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT)
|
|
88
|
+
types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),
|
|
89
|
+
live: true
|
|
89
90
|
}), deadline - Date.now(), `Weglot dynamic translation to ${locale}`);
|
|
90
91
|
chunk.forEach((word, index) => {
|
|
91
92
|
const result = translated[index];
|
|
92
|
-
if (result ===
|
|
93
|
+
if (result === null) logger.debug(`Weglot is still translating dynamic content for locale "${locale}".`);
|
|
94
|
+
else if (result === word.text) logger.debug(`Weglot returned dynamic content unchanged for locale "${locale}".`);
|
|
93
95
|
word.resolve(result ?? word.text);
|
|
94
96
|
});
|
|
95
97
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate-dynamic.mjs","names":["config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\">","chunks: PendingWord[][]"],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":["/**\n * Runtime translation for content the compiler cannot see — a CMS title, an API\n * record. No cache: the API already stores repeated segments.\n */\n\nimport { cache } from \"react\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { WORD_TYPE } from \"../translators/weglot/definitions/definitions.generated\";\nimport { HtmlSegmenter } from \"./html/segmenter\";\nimport { translationEngine } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../utils/logger\";\nimport { withTimeout } from \"../utils/timeout\";\nimport type { LocaleCode } from \"../locale\";\n// Keep these imports full for replacement during build.\nimport { apiLocales, sourceLocale } from \"@weglot/translate-react/virtual/config\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\n\n/** Matches the translate API's own limit, as in the build-time translator. */\nconst MAX_WORDS_PER_REQUEST = 100;\n\n/** Batches are shared across concurrent renders, so a busy server queues many pages. */\nconst MAX_CONCURRENT_REQUESTS = 4;\n\n/** Collection window: server components render concurrently, so this gathers a\n * whole page into one call. */\nconst DEFAULT_BATCH_WINDOW_MS = 5;\n\n/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm\n * call and cuts off a cold one. */\nconst DEFAULT_TIMEOUT_MS = 500;\n\nexport interface DynamicTranslationOptions {\n /** Overrides the locale resolved from the request. */\n locale?: LocaleCode;\n /** Overrides the per-call ceiling before the source text is served. */\n timeoutMs?: number;\n}\n\nexport interface DynamicTranslationConfig {\n apiKey?: string;\n timeoutMs?: number;\n batchWindowMs?: number;\n}\n\nlet config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\"> = {\n apiKey: undefined,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n batchWindowMs: DEFAULT_BATCH_WINDOW_MS,\n};\n\n/** Optional: the key otherwise comes from WEGLOT_API_KEY. */\nexport function configureDynamicTranslation(\n next: DynamicTranslationConfig,\n): void {\n config = { ...config, ...next };\n}\n\nfunction resolveApiKey(): string | undefined {\n return config.apiKey ?? process.env.WEGLOT_API_KEY;\n}\n\ninterface PendingWord {\n text: string;\n type?: number;\n resolve: (translated: string) => void;\n}\n\n/** Keyed by ceiling too, or the stricter call would inherit the looser one's wait. */\ntype BatchKey = string;\n\nconst queues = new Map<BatchKey, PendingWord[]>();\nconst timers = new Map<BatchKey, ReturnType<typeof setTimeout>>();\n\nconst batchKey = (locale: LocaleCode, timeoutMs: number): BatchKey =>\n `${locale}\\u0000${timeoutMs}`;\n\n/** One map per request, so a title rendered twice is translated once. Outside a\n * render, `cache` has nothing to key on and calls stand alone. */\nconst requestMemo = cache(() => new Map<string, Promise<string>>());\n\nfunction memoFor(): Map<string, Promise<string>> | null {\n try {\n return requestMemo();\n } catch {\n return null;\n }\n}\n\nfunction enqueue(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type?: number,\n): Promise<string> {\n const key = batchKey(locale, timeoutMs);\n return new Promise<string>((resolve) => {\n const queue = queues.get(key) ?? [];\n queue.push({ text, type, resolve });\n queues.set(key, queue);\n\n if (!timers.has(key)) {\n timers.set(\n key,\n setTimeout(\n () => void flush(key, locale, timeoutMs),\n config.batchWindowMs,\n ),\n );\n }\n });\n}\n\nasync function flush(\n key: BatchKey,\n locale: LocaleCode,\n timeoutMs: number,\n): Promise<void> {\n timers.delete(key);\n const queue = queues.get(key) ?? [];\n queues.delete(key);\n if (queue.length === 0) return;\n\n const apiKey = resolveApiKey();\n if (!apiKey) {\n logger.warn(\n \"Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).\",\n );\n queue.forEach((word) => word.resolve(word.text));\n return;\n }\n\n const client = new WeglotApiClient(apiKey);\n\n const chunks: PendingWord[][] = [];\n for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) {\n chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));\n }\n\n // One deadline for the batch: chunks sent in turn would multiply the ceiling.\n // The pool bounds the burst, since the ceiling cannot recall a sent request.\n const deadline = Date.now() + timeoutMs;\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < chunks.length) {\n const chunk = chunks[next++];\n if (Date.now() >= deadline) {\n chunk.forEach((word) => word.resolve(word.text));\n continue;\n }\n\n try {\n const translated = await withTimeout(\n client.translate({\n from: sourceLocale,\n to: apiLocales[locale] ?? locale,\n words: chunk.map((word) => word.text),\n types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),\n }),\n deadline - Date.now(),\n `Weglot dynamic translation to ${locale}`,\n );\n\n chunk.forEach((word, index) => {\n const result = translated[index];\n if (result === word.text) {\n // The API echoes a segment back when it rejects it.\n logger.debug(\n `Weglot returned dynamic content unchanged for locale \"${locale}\".`,\n );\n }\n word.resolve(result ?? word.text);\n });\n } catch (error) {\n // A slow or failing API must degrade to source text, never break a page.\n logger.warn(\n `Dynamic translation to \"${locale}\" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`,\n );\n chunk.forEach((word) => word.resolve(word.text));\n }\n }\n };\n\n await Promise.all(\n Array.from(\n { length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) },\n worker,\n ),\n );\n}\n\n/** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */\nexport async function tDynamic(\n text: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!text.trim()) return text;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return text;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const memo = memoFor();\n const key = `${batchKey(locale, timeoutMs)}\\u0000${text}`;\n const existing = memo?.get(key);\n if (existing) return existing;\n\n const pending = enqueue(locale, text, timeoutMs);\n memo?.set(key, pending);\n return pending;\n}\n\n/**\n * Translate an HTML fragment, split into segments the way the proxy splits a\n * page, so a sentence wrapped in `<strong>` travels whole.\n */\nexport async function tDynamicHtml(\n html: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!html.trim()) return html;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return html;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const segmenter = new HtmlSegmenter(html, translationEngine);\n const segments = segmenter.extract();\n if (segments.length === 0) return html;\n\n const translated = await Promise.all(\n segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)),\n );\n return segmenter.apply(translated);\n}\n\n/** Translates several strings in one pass, sharing a single request. */\nexport async function tDynamicAll(\n texts: string[],\n options: DynamicTranslationOptions = {},\n): Promise<string[]> {\n return Promise.all(texts.map((text) => tDynamic(text, options)));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,MAAM,wBAAwB;;AAG9B,MAAM,0BAA0B;AAuBhC,IAAIA,SAGyC;CAC3C,QAAQ;CACR,WApByB;CAqBzB,eAzB8B;CA0B/B;;AAGD,SAAgB,4BACd,MACM;AACN,UAAS;EAAE,GAAG;EAAQ,GAAG;EAAM;;AAGjC,SAAS,gBAAoC;AAC3C,QAAO,OAAO,UAAU,QAAQ,IAAI;;AAYtC,MAAM,yBAAS,IAAI,KAA8B;AACjD,MAAM,yBAAS,IAAI,KAA8C;AAEjE,MAAM,YAAY,QAAoB,cACpC,GAAG,OAAO,QAAQ;;;AAIpB,MAAM,cAAc,4BAAY,IAAI,KAA8B,CAAC;AAEnE,SAAS,UAA+C;AACtD,KA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AAc,MAAM,kBAAkB;CAC5D,MAAM,WAAW,UAAU,SAAS;AACpC,KAAI,SAAS,WAAW,EAAG,QAAO;CAElC,MAAM,aAAa,MAAM,QAAQ,IAC/B,SAAS,KAAK,YAAY,QAAQ,QAAQ,QAAQ,GAAG,WAAW,QAAQ,EAAE,CAAC,CAC5E;AACD,QAAO,UAAU,MAAM,WAAW;;;AAIpC,eAAsB,YACpB,OACA,UAAqC,EAAE,EACpB;AACnB,QAAO,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,MAAM,QAAQ,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"translate-dynamic.mjs","names":["config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\">","chunks: PendingWord[][]"],"sources":["../../src/runtime/translate-dynamic.ts"],"sourcesContent":["/**\n * Runtime translation for content the compiler cannot see — a CMS title, an API\n * record. No cache: the API already stores repeated segments.\n */\n\nimport { cache } from \"react\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { WORD_TYPE } from \"../translators/weglot/definitions/definitions.generated\";\nimport { HtmlSegmenter } from \"./html/segmenter\";\nimport { translationEngine } from \"@weglot/translate-react/virtual/config\";\nimport { logger } from \"../utils/logger\";\nimport { withTimeout } from \"../utils/timeout\";\nimport type { LocaleCode } from \"../locale\";\n// Keep these imports full for replacement during build.\nimport {\n apiBaseUrl,\n apiLocales,\n sourceLocale,\n} from \"@weglot/translate-react/virtual/config\";\nimport { getServerLocale } from \"@weglot/translate-react/virtual/locale/server\";\n\n/** Matches the translate API's own limit, as in the build-time translator. */\nconst MAX_WORDS_PER_REQUEST = 100;\n\n/** Batches are shared across concurrent renders, so a busy server queues many pages. */\nconst MAX_CONCURRENT_REQUESTS = 4;\n\n/** Collection window: server components render concurrently, so this gathers a\n * whole page into one call. */\nconst DEFAULT_BATCH_WINDOW_MS = 5;\n\n/** Measured round trips are ~150ms warm and ~750ms cold: this clears a warm\n * call and cuts off a cold one. */\nconst DEFAULT_TIMEOUT_MS = 500;\n\nexport interface DynamicTranslationOptions {\n /** Overrides the locale resolved from the request. */\n locale?: LocaleCode;\n /** Overrides the per-call ceiling before the source text is served. */\n timeoutMs?: number;\n}\n\nexport interface DynamicTranslationConfig {\n apiKey?: string;\n timeoutMs?: number;\n batchWindowMs?: number;\n}\n\nlet config: Required<\n Pick<DynamicTranslationConfig, \"timeoutMs\" | \"batchWindowMs\">\n> &\n Pick<DynamicTranslationConfig, \"apiKey\"> = {\n apiKey: undefined,\n timeoutMs: DEFAULT_TIMEOUT_MS,\n batchWindowMs: DEFAULT_BATCH_WINDOW_MS,\n};\n\n/** Optional: the key otherwise comes from WEGLOT_API_KEY. */\nexport function configureDynamicTranslation(\n next: DynamicTranslationConfig,\n): void {\n config = { ...config, ...next };\n}\n\nfunction resolveApiKey(): string | undefined {\n return config.apiKey ?? process.env.WEGLOT_API_KEY;\n}\n\ninterface PendingWord {\n text: string;\n type?: number;\n resolve: (translated: string) => void;\n}\n\n/** Keyed by ceiling too, or the stricter call would inherit the looser one's wait. */\ntype BatchKey = string;\n\nconst queues = new Map<BatchKey, PendingWord[]>();\nconst timers = new Map<BatchKey, ReturnType<typeof setTimeout>>();\n\nconst batchKey = (locale: LocaleCode, timeoutMs: number): BatchKey =>\n `${locale}\\u0000${timeoutMs}`;\n\n/** One map per request, so a title rendered twice is translated once. Outside a\n * render, `cache` has nothing to key on and calls stand alone. */\nconst requestMemo = cache(() => new Map<string, Promise<string>>());\n\nfunction memoFor(): Map<string, Promise<string>> | null {\n try {\n return requestMemo();\n } catch {\n return null;\n }\n}\n\nfunction enqueue(\n locale: LocaleCode,\n text: string,\n timeoutMs: number,\n type?: number,\n): Promise<string> {\n const key = batchKey(locale, timeoutMs);\n return new Promise<string>((resolve) => {\n const queue = queues.get(key) ?? [];\n queue.push({ text, type, resolve });\n queues.set(key, queue);\n\n if (!timers.has(key)) {\n timers.set(\n key,\n setTimeout(\n () => void flush(key, locale, timeoutMs),\n config.batchWindowMs,\n ),\n );\n }\n });\n}\n\nasync function flush(\n key: BatchKey,\n locale: LocaleCode,\n timeoutMs: number,\n): Promise<void> {\n timers.delete(key);\n const queue = queues.get(key) ?? [];\n queues.delete(key);\n if (queue.length === 0) return;\n\n const apiKey = resolveApiKey();\n if (!apiKey) {\n logger.warn(\n \"Weglot project key is missing, so dynamic content is served untranslated. Set WEGLOT_API_KEY or call configureDynamicTranslation({ apiKey }).\",\n );\n queue.forEach((word) => word.resolve(word.text));\n return;\n }\n\n const client = new WeglotApiClient(apiKey, apiBaseUrl);\n\n const chunks: PendingWord[][] = [];\n for (let i = 0; i < queue.length; i += MAX_WORDS_PER_REQUEST) {\n chunks.push(queue.slice(i, i + MAX_WORDS_PER_REQUEST));\n }\n\n // One deadline for the batch: chunks sent in turn would multiply the ceiling.\n // The pool bounds the burst, since the ceiling cannot recall a sent request.\n const deadline = Date.now() + timeoutMs;\n let next = 0;\n\n const worker = async (): Promise<void> => {\n while (next < chunks.length) {\n const chunk = chunks[next++];\n if (Date.now() >= deadline) {\n chunk.forEach((word) => word.resolve(word.text));\n continue;\n }\n\n try {\n const translated = await withTimeout(\n client.translate({\n from: sourceLocale,\n to: apiLocales[locale] ?? locale,\n words: chunk.map((word) => word.text),\n types: chunk.map((word) => word.type ?? WORD_TYPE.TEXT),\n live: true,\n }),\n deadline - Date.now(),\n `Weglot dynamic translation to ${locale}`,\n );\n\n chunk.forEach((word, index) => {\n const result = translated[index];\n if (result === null) {\n // Still generating at Weglot; a later request gets the translation.\n logger.debug(\n `Weglot is still translating dynamic content for locale \"${locale}\".`,\n );\n } else if (result === word.text) {\n // The API echoes a segment back when it rejects it.\n logger.debug(\n `Weglot returned dynamic content unchanged for locale \"${locale}\".`,\n );\n }\n word.resolve(result ?? word.text);\n });\n } catch (error) {\n // A slow or failing API must degrade to source text, never break a page.\n logger.warn(\n `Dynamic translation to \"${locale}\" failed, serving source text: ${error instanceof Error ? error.message : String(error)}`,\n );\n chunk.forEach((word) => word.resolve(word.text));\n }\n }\n };\n\n await Promise.all(\n Array.from(\n { length: Math.min(MAX_CONCURRENT_REQUESTS, chunks.length) },\n worker,\n ),\n );\n}\n\n/** Translate a string that only exists at runtime: `await tDynamic(post.title)`. */\nexport async function tDynamic(\n text: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!text.trim()) return text;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return text;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const memo = memoFor();\n const key = `${batchKey(locale, timeoutMs)}\\u0000${text}`;\n const existing = memo?.get(key);\n if (existing) return existing;\n\n const pending = enqueue(locale, text, timeoutMs);\n memo?.set(key, pending);\n return pending;\n}\n\n/**\n * Translate an HTML fragment, split into segments the way the proxy splits a\n * page, so a sentence wrapped in `<strong>` travels whole.\n */\nexport async function tDynamicHtml(\n html: string,\n options: DynamicTranslationOptions = {},\n): Promise<string> {\n if (!html.trim()) return html;\n\n const locale = options.locale ?? (await getServerLocale());\n if (!locale || locale === sourceLocale) return html;\n\n const timeoutMs = options.timeoutMs ?? config.timeoutMs;\n const segmenter = new HtmlSegmenter(html, translationEngine);\n const segments = segmenter.extract();\n if (segments.length === 0) return html;\n\n const translated = await Promise.all(\n segments.map((segment) => enqueue(locale, segment.w, timeoutMs, segment.t)),\n );\n return segmenter.apply(translated);\n}\n\n/** Translates several strings in one pass, sharing a single request. */\nexport async function tDynamicAll(\n texts: string[],\n options: DynamicTranslationOptions = {},\n): Promise<string[]> {\n return Promise.all(texts.map((text) => tDynamic(text, options)));\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,wBAAwB;;AAG9B,MAAM,0BAA0B;AAuBhC,IAAIA,SAGyC;CAC3C,QAAQ;CACR,WApByB;CAqBzB,eAzB8B;CA0B/B;;AAGD,SAAgB,4BACd,MACM;AACN,UAAS;EAAE,GAAG;EAAQ,GAAG;EAAM;;AAGjC,SAAS,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Q,QAAQ,MAAM,UAAU;AAChD,OAAM,IAAI,KAAK,QAAQ;AACvB,QAAO;;;;;;AAOT,eAAsB,aACpB,MACA,UAAqC,EAAE,EACtB;AACjB,KAAI,CAAC,KAAK,MAAM,CAAE,QAAO;CAEzB,MAAM,SAAS,QAAQ,UAAW,MAAM,iBAAiB;AACzD,KAAI,CAAC,UAAU,WAAW,aAAc,QAAO;CAE/C,MAAM,YAAY,QAAQ,aAAa,OAAO;CAC9C,MAAM,YAAY,IAAI,cAAc,MAAM,kBAAkB;CAC5D,MAAM,WAAW,UAAU,SAAS;AACpC,KAAI,SAAS,WAAW,EAAG,QAAO;CAElC,MAAM,aAAa,MAAM,QAAQ,IAC/B,SAAS,KAAK,YAAY,QAAQ,QAAQ,QAAQ,GAAG,WAAW,QAAQ,EAAE,CAAC,CAC5E;AACD,QAAO,UAAU,MAAM,WAAW;;;AAIpC,eAAsB,YACpB,OACA,UAAqC,EAAE,EACpB;AACnB,QAAO,QAAQ,IAAI,MAAM,KAAK,SAAS,SAAS,MAAM,QAAQ,CAAC,CAAC"}
|
|
@@ -14,7 +14,9 @@ var TranslationService = class {
|
|
|
14
14
|
apiKey: config.apiKey,
|
|
15
15
|
sourceLocale: config.sourceLocale,
|
|
16
16
|
apiLocales: config.apiLocales,
|
|
17
|
-
translationEngine: config.translationEngine
|
|
17
|
+
translationEngine: config.translationEngine,
|
|
18
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
19
|
+
translationTimeoutMs: config.translationTimeout * 1e3
|
|
18
20
|
}, this.logger);
|
|
19
21
|
}
|
|
20
22
|
/**
|
|
@@ -82,7 +84,7 @@ var TranslationService = class {
|
|
|
82
84
|
errors.push({
|
|
83
85
|
hash,
|
|
84
86
|
sourceText: entry?.sourceText || "",
|
|
85
|
-
error: "
|
|
87
|
+
error: "No translation returned yet; Weglot may still be generating it"
|
|
86
88
|
});
|
|
87
89
|
}
|
|
88
90
|
}
|
|
@@ -14,7 +14,9 @@ var TranslationService = class {
|
|
|
14
14
|
apiKey: config.apiKey,
|
|
15
15
|
sourceLocale: config.sourceLocale,
|
|
16
16
|
apiLocales: config.apiLocales,
|
|
17
|
-
translationEngine: config.translationEngine
|
|
17
|
+
translationEngine: config.translationEngine,
|
|
18
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
19
|
+
translationTimeoutMs: config.translationTimeout * 1e3
|
|
18
20
|
}, this.logger);
|
|
19
21
|
}
|
|
20
22
|
/**
|
|
@@ -82,7 +84,7 @@ var TranslationService = class {
|
|
|
82
84
|
errors.push({
|
|
83
85
|
hash,
|
|
84
86
|
sourceText: entry?.sourceText || "",
|
|
85
|
-
error: "
|
|
87
|
+
error: "No translation returned yet; Weglot may still be generating it"
|
|
86
88
|
});
|
|
87
89
|
}
|
|
88
90
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; derived from the key length when absent. */\n translationEngine?: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"Translator doesn't return translation\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AA+DA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;AAER,OAAK,QAAQ,YAAY,OAAO;AAChC,OAAK,aAAa,IAAI,iBACpB;GACE,QAAQ,OAAO;GACf,cAAc,OAAO;GACrB,YAAY,OAAO;GACnB,mBAAmB,OAAO;GAC3B,EACD,KAAK,OACN;;;;;;;;;;CAWH,MAAM,UACJ,QACA,UACA,iBAC4B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AAMC,UAA6C,EAAE;AAErD,OAAK,MAAM,QAAQ,QAAQ;GACzB,MAAM,QAAQ,SAAS;AACvB,OAAI,MACF,SAAQ,QAAQ;IACd,MAAM,MAAM;IACZ,SAAS,MAAM,WAAW,EAAE;IAC7B;;AAIL,SAAO;;;;;CAOT,AAAQ,iBACN,iBACA,iBACwB;EACxB,MAAMC,SAAiC,EAAE;AAEzC,OAAK,MAAM,QAAQ,gBACjB,KAAI,gBAAgB,MAClB,QAAO,QAAQ,gBAAgB;AAInC,SAAO"}
|
|
1
|
+
{"version":3,"file":"translation-service.mjs","names":["config: TranslationServiceConfig","logger: Logger","filteredMetadata: MetadataSchema","newTranslations: Record<string, string>","errors: TranslationError[]","entries: Record<string, TranslatableEntry>","result: Record<string, string>"],"sources":["../../src/translators/translation-service.ts"],"sourcesContent":["/**\n * TranslationService - Main orchestrator for translation workflow\n *\n * Responsibilities:\n * - Coordinates between metadata, cache, and translator\n * - Determines what needs translation\n * - Handles caching strategy\n * - Manages partial failures\n */\n\nimport type { TranslationCache } from \"./cache\";\nimport type { TranslatableEntry, Translator } from \"./api\";\nimport type { WeglotEnvironment, MetadataSchema } from \"../types\";\nimport type { Logger } from \"../utils/logger\";\nimport type { LocaleCode } from \"../locale\";\nimport { UnsupportedLanguagePairError, WeglotTranslator } from \"./weglot\";\nimport { type CacheConfig, createCache } from \"./cache-factory\";\n\nexport type TranslationServiceConfig = {\n /**\n * Weglot project API key\n */\n apiKey: string;\n\n /**\n * Source locale (e.g., \"en\")\n */\n sourceLocale: LocaleCode;\n\n /** Public locale to the language code the translate API expects. */\n apiLocales?: Record<string, LocaleCode>;\n\n /** From the project settings; the modern engine when absent. */\n translationEngine?: number;\n\n /** The project's regional API host, from the project settings. */\n apiBaseUrl?: string;\n\n /** Seconds to wait for translations Weglot is still generating. */\n translationTimeout: number;\n\n environment: WeglotEnvironment;\n} & CacheConfig;\n\nexport interface TranslationResult {\n /**\n * Successfully translated entries (hash -> translated text)\n */\n translations: Record<string, string>;\n\n errors: TranslationError[];\n\n /** The API refuses this target, so callers report it and move on. */\n unsupportedLocale?: boolean;\n\n stats: {\n total: number;\n cached: number;\n translated: number;\n failed: number;\n };\n}\n\nexport interface TranslationError {\n hash: string;\n sourceText: string;\n error: string;\n}\n\nexport class TranslationService {\n private translator: Translator<any>;\n private cache: TranslationCache;\n\n constructor(\n private config: TranslationServiceConfig,\n private logger: Logger,\n ) {\n this.cache = createCache(config);\n this.translator = new WeglotTranslator(\n {\n apiKey: config.apiKey,\n sourceLocale: config.sourceLocale,\n apiLocales: config.apiLocales,\n translationEngine: config.translationEngine,\n apiBaseUrl: config.apiBaseUrl,\n translationTimeoutMs: config.translationTimeout * 1000,\n },\n this.logger,\n );\n }\n\n /**\n * Translate entries to target locale\n *\n * @param locale Target locale (including source locale)\n * @param metadata Metadata schema with all entries\n * @param requestedHashes Optional: only translate specific hashes\n * @returns Translation result with translations and errors\n */\n async translate(\n locale: LocaleCode,\n metadata: MetadataSchema,\n requestedHashes?: string[],\n ): Promise<TranslationResult> {\n const startTime = performance.now();\n\n // Step 1: Determine which hashes we need to work with\n const workingHashes = requestedHashes || Object.keys(metadata);\n\n this.logger.debug(\n `Translation requested for ${workingHashes.length} hashes in locale: ${locale}`,\n );\n\n // Step 2: Check cache first (same for all locales, including source)\n const cachedTranslations = await this.cache.get(locale);\n\n // Step 3: Determine what needs translation\n const uncachedHashes = workingHashes.filter(\n (hash) => !cachedTranslations[hash],\n );\n this.logger.debug(\n `${uncachedHashes.length} hashes need processing, ${workingHashes.length - uncachedHashes.length} are cached`,\n );\n\n const cachedCount = workingHashes.length - uncachedHashes.length;\n\n if (uncachedHashes.length === 0) {\n return {\n translations: this.pickTranslations(cachedTranslations, workingHashes),\n errors: [],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: 0,\n },\n };\n }\n\n this.logger.debug(\n `Generating translations for ${uncachedHashes.length} uncached hashes in ${locale}...`,\n );\n\n // Step 4: Filter metadata to only uncached entries\n const filteredMetadata: MetadataSchema = Object.fromEntries(\n uncachedHashes\n .map((hash) => [hash, metadata[hash]])\n .filter(([_, entry]) => entry !== undefined),\n );\n\n // Step 5: Prepare entries for translation\n const entriesToTranslate = this.prepareEntries(\n filteredMetadata,\n uncachedHashes,\n );\n\n // Step 6: Translate or return source text\n let newTranslations: Record<string, string> = {};\n const errors: TranslationError[] = [];\n\n if (locale === this.config.sourceLocale) {\n // For source locale, just return the sourceText\n this.logger.debug(\n `Source locale detected, returning sourceText for ${uncachedHashes.length} entries`,\n );\n for (const [hash, entry] of Object.entries(entriesToTranslate)) {\n newTranslations[hash] = entry.text;\n }\n } else if (Object.keys(entriesToTranslate).length > 0) {\n // For other locales, translate entries\n try {\n this.logger.debug(\n `Translating ${locale} with ${Object.keys(entriesToTranslate).length} entries`,\n );\n const translatedTexts = await this.translator.translate(\n locale,\n entriesToTranslate,\n );\n newTranslations = { ...translatedTexts };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const unsupportedLocale = error instanceof UnsupportedLanguagePairError;\n if (unsupportedLocale) {\n this.logger.warn(\n `Locale \"${locale}\" cannot be translated: ${errorMessage}`,\n );\n } else {\n this.logger.error(\n `Translation failed for locale \"${locale}\": ${errorMessage}`,\n );\n }\n if (error instanceof Error && error.stack) {\n this.logger.debug(`Stack trace: ${error.stack}`);\n }\n\n return {\n unsupportedLocale,\n translations: this.pickTranslations(\n cachedTranslations,\n workingHashes,\n ),\n errors: [\n {\n hash: \"all\",\n sourceText: \"all\",\n error: errorMessage,\n },\n ],\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: 0,\n failed: uncachedHashes.length,\n },\n };\n }\n\n // Check for partial failures (some hashes didn't get translated)\n for (const hash of uncachedHashes) {\n if (!newTranslations[hash]) {\n const entry = filteredMetadata[hash];\n errors.push({\n hash,\n sourceText: entry?.sourceText || \"\",\n error: \"No translation returned yet; Weglot may still be generating it\",\n });\n }\n }\n }\n\n // Step 7: Update cache with successful translations\n if (Object.keys(newTranslations).length > 0) {\n try {\n await this.cache.update(locale, newTranslations);\n } catch (error) {\n this.logger.error(`Failed to update cache:`, error);\n // Don't fail the request if cache update fails\n }\n }\n\n // Step 8: Merge and return\n const allTranslations = { ...cachedTranslations, ...newTranslations };\n const result = this.pickTranslations(allTranslations, workingHashes);\n\n const endTime = performance.now();\n this.logger.debug(\n `Translation completed for ${locale}: ${Object.keys(newTranslations).length} new, ${cachedCount} cached, ${errors.length} errors in ${(endTime - startTime).toFixed(2)}ms`,\n );\n\n return {\n translations: result,\n errors,\n stats: {\n total: workingHashes.length,\n cached: cachedCount,\n translated: Object.keys(newTranslations).length,\n failed: errors.length,\n },\n };\n }\n\n /**\n * Prepare metadata entries for translation\n */\n private prepareEntries(\n metadata: MetadataSchema,\n hashes: string[],\n ): Record<string, TranslatableEntry> {\n const entries: Record<string, TranslatableEntry> = {};\n\n for (const hash of hashes) {\n const entry = metadata[hash];\n if (entry) {\n entries[hash] = {\n text: entry.sourceText,\n context: entry.context || {},\n };\n }\n }\n\n return entries;\n }\n\n /**\n * Pick only requested translations from the full set\n */\n // TODO (AleksandrSl 14/12/2025): SHould I use this in the build somehow?\n private pickTranslations(\n allTranslations: Record<string, string>,\n requestedHashes: string[],\n ): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const hash of requestedHashes) {\n if (allTranslations[hash]) {\n result[hash] = allTranslations[hash];\n }\n }\n\n return result;\n }\n}\n"],"mappings":";;;;;AAqEA,IAAa,qBAAb,MAAgC;CAC9B,AAAQ;CACR,AAAQ;CAER,YACE,AAAQA,QACR,AAAQC,QACR;EAFQ;EACA;AAER,OAAK,QAAQ,YAAY,OAAO;AAChC,OAAK,aAAa,IAAI,iBACpB;GACE,QAAQ,OAAO;GACf,cAAc,OAAO;GACrB,YAAY,OAAO;GACnB,mBAAmB,OAAO;GAC1B,YAAY,OAAO;GACnB,sBAAsB,OAAO,qBAAqB;GACnD,EACD,KAAK,OACN;;;;;;;;;;CAWH,MAAM,U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