@weglot/translate-react 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +118 -12
  2. package/build/metadata/manager.cjs +18 -5
  3. package/build/metadata/manager.mjs +17 -5
  4. package/build/metadata/manager.mjs.map +1 -1
  5. package/build/plugin/next-compiler-loader.cjs +1 -4
  6. package/build/plugin/next-compiler-loader.mjs +2 -5
  7. package/build/plugin/next-compiler-loader.mjs.map +1 -1
  8. package/build/plugin/next-traces.cjs +38 -0
  9. package/build/plugin/next-traces.mjs +36 -0
  10. package/build/plugin/next-traces.mjs.map +1 -0
  11. package/build/plugin/next.cjs +43 -12
  12. package/build/plugin/next.d.cts.map +1 -1
  13. package/build/plugin/next.d.mts.map +1 -1
  14. package/build/plugin/next.mjs +41 -13
  15. package/build/plugin/next.mjs.map +1 -1
  16. package/build/plugin/transform/index.cjs +17 -3
  17. package/build/plugin/transform/index.mjs +17 -3
  18. package/build/plugin/transform/index.mjs.map +1 -1
  19. package/build/plugin/transform/msg.cjs +66 -0
  20. package/build/plugin/transform/msg.mjs +64 -0
  21. package/build/plugin/transform/msg.mjs.map +1 -0
  22. package/build/plugin/transform/process-file.cjs +18 -7
  23. package/build/plugin/transform/process-file.mjs +18 -7
  24. package/build/plugin/transform/process-file.mjs.map +1 -1
  25. package/build/plugin/transform/utils.cjs +1 -0
  26. package/build/plugin/transform/utils.mjs +1 -1
  27. package/build/plugin/transform/utils.mjs.map +1 -1
  28. package/build/plugin/unplugin.cjs +6 -7
  29. package/build/plugin/unplugin.d.cts.map +1 -1
  30. package/build/plugin/unplugin.d.mts.map +1 -1
  31. package/build/plugin/unplugin.mjs +7 -8
  32. package/build/plugin/unplugin.mjs.map +1 -1
  33. package/build/react/client/index.cjs +2 -0
  34. package/build/react/client/index.d.cts +2 -1
  35. package/build/react/client/index.d.mts +2 -1
  36. package/build/react/client/index.mjs +2 -1
  37. package/build/react/client/useTranslation.cjs +14 -2
  38. package/build/react/client/useTranslation.d.cts +0 -35
  39. package/build/react/client/useTranslation.d.cts.map +1 -1
  40. package/build/react/client/useTranslation.d.mts +0 -35
  41. package/build/react/client/useTranslation.d.mts.map +1 -1
  42. package/build/react/client/useTranslation.mjs +15 -3
  43. package/build/react/client/useTranslation.mjs.map +1 -1
  44. package/build/react/server/ServerWeglotProvider.d.cts +2 -2
  45. package/build/react/server/ServerWeglotProvider.d.mts +2 -2
  46. package/build/react/server/index.cjs +2 -0
  47. package/build/react/server/index.d.cts +2 -1
  48. package/build/react/server/index.d.mts +2 -1
  49. package/build/react/server/index.mjs +2 -1
  50. package/build/react/server/useTranslation.cjs +6 -4
  51. package/build/react/server/useTranslation.d.cts.map +1 -1
  52. package/build/react/server/useTranslation.d.mts.map +1 -1
  53. package/build/react/server/useTranslation.mjs +6 -4
  54. package/build/react/server/useTranslation.mjs.map +1 -1
  55. package/build/react/server-only/index.cjs +5 -3
  56. package/build/react/server-only/index.d.cts +2 -3
  57. package/build/react/server-only/index.d.cts.map +1 -1
  58. package/build/react/server-only/index.d.mts +2 -3
  59. package/build/react/server-only/index.d.mts.map +1 -1
  60. package/build/react/server-only/index.mjs +5 -3
  61. package/build/react/server-only/index.mjs.map +1 -1
  62. package/build/react/server-only/translations.cjs +21 -1
  63. package/build/react/server-only/translations.mjs +22 -2
  64. package/build/react/server-only/translations.mjs.map +1 -1
  65. package/build/react/shared/LocaleSwitcher.d.mts +2 -2
  66. package/build/react/shared/WeglotContext.cjs +18 -2
  67. package/build/react/shared/WeglotContext.d.cts +1 -0
  68. package/build/react/shared/WeglotContext.d.cts.map +1 -1
  69. package/build/react/shared/WeglotContext.d.mts +2 -0
  70. package/build/react/shared/WeglotContext.d.mts.map +1 -1
  71. package/build/react/shared/WeglotContext.mjs +18 -2
  72. package/build/react/shared/WeglotContext.mjs.map +1 -1
  73. package/build/react/shared/WeglotProvider.cjs +4 -0
  74. package/build/react/shared/WeglotProvider.d.cts +2 -2
  75. package/build/react/shared/WeglotProvider.d.cts.map +1 -1
  76. package/build/react/shared/WeglotProvider.d.mts +2 -2
  77. package/build/react/shared/WeglotProvider.d.mts.map +1 -1
  78. package/build/react/shared/WeglotProvider.mjs +4 -0
  79. package/build/react/shared/WeglotProvider.mjs.map +1 -1
  80. package/build/react/shared/msg.cjs +50 -0
  81. package/build/react/shared/msg.d.cts +26 -0
  82. package/build/react/shared/msg.d.cts.map +1 -0
  83. package/build/react/shared/msg.d.mts +26 -0
  84. package/build/react/shared/msg.d.mts.map +1 -0
  85. package/build/react/shared/msg.mjs +47 -0
  86. package/build/react/shared/msg.mjs.map +1 -0
  87. package/build/react/types.d.cts +7 -3
  88. package/build/react/types.d.cts.map +1 -1
  89. package/build/react/types.d.mts +7 -3
  90. package/build/react/types.d.mts.map +1 -1
  91. package/build/runtime/lru-cache.cjs +38 -0
  92. package/build/runtime/lru-cache.mjs +38 -0
  93. package/build/runtime/lru-cache.mjs.map +1 -0
  94. package/build/runtime/translate-dynamic.cjs +71 -17
  95. package/build/runtime/translate-dynamic.d.cts +2 -0
  96. package/build/runtime/translate-dynamic.d.cts.map +1 -1
  97. package/build/runtime/translate-dynamic.d.mts +2 -0
  98. package/build/runtime/translate-dynamic.d.mts.map +1 -1
  99. package/build/runtime/translate-dynamic.mjs +71 -17
  100. package/build/runtime/translate-dynamic.mjs.map +1 -1
  101. package/build/translators/weglot/api-client.cjs +4 -1
  102. package/build/translators/weglot/api-client.mjs +4 -1
  103. package/build/translators/weglot/api-client.mjs.map +1 -1
  104. package/build/types.d.cts +7 -1
  105. package/build/types.d.cts.map +1 -1
  106. package/build/types.d.mts +7 -1
  107. package/build/types.d.mts.map +1 -1
  108. package/build/utils/package-version.cjs +12 -0
  109. package/build/utils/package-version.mjs +12 -0
  110. package/build/utils/package-version.mjs.map +1 -0
  111. package/package.json +4 -2
@@ -2,18 +2,24 @@ import { __require } from "../_virtual/rolldown_runtime.mjs";
2
2
  import { logger } from "../utils/logger.mjs";
3
3
  import { createWeglotConfig, resolveProjectLanguages } from "../utils/config-factory.mjs";
4
4
  import { TranslationService } from "../translators/translation-service.mjs";
5
- import { cleanupMetadataForEnvironment, getMetadataPath } from "../metadata/manager.mjs";
5
+ import { getMetadataPath, loadMetadata, pruneMetadata } from "../metadata/manager.mjs";
6
6
  import { startOrGetTranslationServer } from "../translation-server/translation-server.mjs";
7
7
  import { processBuildTranslations } from "./build-translator.mjs";
8
+ import { addDictionariesToTraces } from "./next-traces.mjs";
8
9
  import { registerCleanupOnCurrentProcess } from "./cleanup.mjs";
9
10
  import { useI18nRegex } from "./transform/use-i18n.mjs";
11
+ import { msgImportRegex } from "./transform/msg.mjs";
12
+ import { packageVersion } from "../utils/package-version.mjs";
13
+ import fs from "node:fs/promises";
14
+ import path from "node:path";
10
15
 
11
16
  //#region src/plugin/next.ts
12
17
  function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
13
18
  const common = {
14
19
  sourceRoot: weglotConfig.sourceRoot,
15
20
  weglotDir: weglotConfig.weglotDir,
16
- sourceLocale: weglotConfig.sourceLocale
21
+ sourceLocale: weglotConfig.sourceLocale,
22
+ version: packageVersion()
17
23
  };
18
24
  const compilerLoader = {
19
25
  loader: "@weglot/translate-react/next-compiler-loader",
@@ -56,17 +62,27 @@ function loaders({ weglotConfig, metadataFilePath, translationServerUrl }) {
56
62
  turbopack: {
57
63
  pattern: "*.{tsx,jsx}",
58
64
  config: {
59
- condition: { content: weglotConfig.useDirective ? useI18nRegex : void 0 },
65
+ condition: weglotConfig.useDirective ? { any: [{ content: useI18nRegex }, { content: msgImportRegex }] } : { content: void 0 },
60
66
  loaders: [compilerLoader]
61
67
  }
62
68
  },
63
69
  webpack: {
64
70
  enforce: "pre",
65
- test: /\.(tsx|jsx)$/i,
71
+ test: /\.(tsx|jsx|[cm]?[jt]s)$/i,
66
72
  exclude: /node_modules/,
67
73
  use: [compilerLoader]
68
74
  }
69
75
  },
76
+ messages: { turbopack: {
77
+ pattern: "*.{ts,js,mts,mjs}",
78
+ config: hasStableTurboConfig() ? {
79
+ condition: { all: [{ not: "foreign" }, { content: msgImportRegex }] },
80
+ loaders: [compilerLoader]
81
+ } : {
82
+ foreign: false,
83
+ default: { loaders: [compilerLoader] }
84
+ }
85
+ } },
70
86
  config: {
71
87
  turbopack: {
72
88
  pattern: "**/virtual/config.mjs",
@@ -133,10 +149,22 @@ function mergeTurbopackRules(existingRules, newRules) {
133
149
  function isMainRunner() {
134
150
  return !process.env.NEXT_PRIVATE_BUILD_WORKER && !process.env.IS_NEXT_WORKER && !process.env.NEXT_PRIVATE_WORKER;
135
151
  }
152
+ async function failOnLostMetadata(metadataFilePath, lastBuildFile) {
153
+ if (Object.keys(await loadMetadata(metadataFilePath, true)).length > 0) return;
154
+ const last = await fs.readFile(lastBuildFile, "utf8").then((content) => JSON.parse(content).entries).catch(() => 0);
155
+ if (last > 0) throw new Error(`No translatable text was found, but the previous build had ${last} entries: the bundler served the files from its cache without the Weglot metadata. Delete ${path.relative(process.cwd(), path.dirname(path.dirname(lastBuildFile)))} and build again.`);
156
+ }
157
+ async function writeLastBuild(metadataFilePath, lastBuildFile) {
158
+ const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;
159
+ await fs.mkdir(path.dirname(lastBuildFile), { recursive: true });
160
+ await fs.writeFile(lastBuildFile, JSON.stringify({ entries }));
161
+ }
136
162
  async function withWeglot(nextConfig = {}, weglotOptions) {
137
163
  const weglotConfig = createWeglotConfig(weglotOptions);
138
164
  await resolveProjectLanguages(weglotConfig);
139
- let metadataFilePath = getMetadataPath(weglotConfig);
165
+ const distDir = path.resolve(nextConfig.distDir ?? ".next");
166
+ if (weglotConfig.environment !== "development") weglotConfig.metadataDir = path.join(distDir, "cache", "weglot", "metadata-build");
167
+ const metadataFilePath = getMetadataPath(weglotConfig);
140
168
  const isDev = weglotConfig.environment === "development";
141
169
  logger.debug(`Initializing Weglot. Is dev mode: ${isDev}. Is main runner: ${isMainRunner()}`);
142
170
  if (isDev && !process.env.WEGLOT_TRANSLATION_SERVER_URL) if (weglotConfig.dev.translationServerUrl) {
@@ -159,11 +187,6 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
159
187
  } });
160
188
  }
161
189
  const translationServerUrl = process.env.WEGLOT_TRANSLATION_SERVER_URL;
162
- if (isMainRunner()) {
163
- const environment = weglotConfig.environment;
164
- cleanupMetadataForEnvironment(metadataFilePath, environment);
165
- registerCleanupOnCurrentProcess({ cleanup: () => cleanupMetadataForEnvironment(metadataFilePath, environment) });
166
- }
167
190
  const existingTurbopackConfig = getTurbopackConfig(nextConfig);
168
191
  let mergedRules = mergeTurbopackRules(existingTurbopackConfig.rules ?? {}, Object.values(loaders({
169
192
  weglotConfig,
@@ -185,18 +208,23 @@ async function withWeglot(nextConfig = {}, weglotOptions) {
185
208
  resolveAlias: mergedResolveAlias
186
209
  }
187
210
  } };
188
- const runAfterProductionCompile = async ({ distDir, projectDir }) => {
211
+ const runAfterProductionCompile = async ({ distDir: distDir$1, projectDir }) => {
189
212
  if (typeof nextConfig.compiler?.runAfterProductionCompile === "function") await nextConfig.compiler.runAfterProductionCompile({
190
- distDir,
213
+ distDir: distDir$1,
191
214
  projectDir
192
215
  });
193
216
  logger.info("Running post-build translation generation...");
217
+ const lastBuildFile = path.join(distDir$1, "cache", "weglot", "last-build.json");
194
218
  try {
219
+ await pruneMetadata(metadataFilePath);
220
+ await failOnLostMetadata(metadataFilePath, lastBuildFile);
195
221
  await processBuildTranslations({
196
222
  config: weglotConfig,
197
- publicOutputPath: distDir,
223
+ publicOutputPath: distDir$1,
198
224
  metadataFilePath
199
225
  });
226
+ await addDictionariesToTraces(distDir$1, weglotConfig.targetLocales);
227
+ await writeLastBuild(metadataFilePath, lastBuildFile);
200
228
  } catch (error) {
201
229
  logger.error("Translation generation failed:", error instanceof Error ? error.message : error);
202
230
  throw error;
@@ -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 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;E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AAC,CAClE,CAAC,KAAK,UAAU,MAAM,UAAU,CAClC;CAGD,MAAM,qBAAqB,EACzB,GAF2B,wBAAwB,cAGpD;CAED,IAAIA;AACJ,KAAI,sBAAsB,CACxB,mBAAkB,EAChB,WAAW;EACT,GAAG,WAAW;EACd,OAAO;EACP,cAAc;EACf,EACF;KAED,mBAAkB,EAChB,cAAc;EACZ,GAAG,WAAW;EAEd,OAAO;GAEL,GAAG,WAAW,cAAc;GAC5B,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>","distDir","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 { addDictionariesToTraces } from \"./next-traces\";\nimport { startOrGetTranslationServer } from \"../translation-server/translation-server\";\nimport { getMetadataPath, loadMetadata, pruneMetadata } from \"../metadata/manager\";\nimport { registerCleanupOnCurrentProcess } from \"./cleanup\";\nimport { useI18nRegex } from \"./transform/use-i18n\";\nimport { msgImportRegex } from \"./transform/msg\";\nimport { TranslationService } from \"../translators\";\nimport { packageVersion } from \"../utils/package-version\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport type WeglotNextPluginOptions = PartialWeglotConfig;\n\ntype RuleKey =\n | \"compiler\"\n | \"messages\"\n | \"config\"\n | \"localeServer\"\n | \"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 // Part of the bundlers' cache key, so an upgrade recompiles cached files.\n version: packageVersion(),\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: weglotConfig.useDirective\n ? { any: [{ content: useI18nRegex }, { content: msgImportRegex }] }\n : { content: undefined },\n loaders: [compilerLoader],\n },\n },\n webpack: {\n enforce: \"pre\",\n test: /\\.(tsx|jsx|[cm]?[jt]s)$/i,\n exclude: /node_modules/,\n use: [compilerLoader],\n },\n },\n\n // .ts/.js files are compiled only for their msg() calls.\n messages: {\n turbopack: {\n pattern: \"*.{ts,js,mts,mjs}\",\n config: hasStableTurboConfig()\n ? {\n condition: {\n all: [{ not: \"foreign\" }, { content: msgImportRegex }],\n },\n loaders: [compilerLoader],\n }\n : { foreign: false, default: { loaders: [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\nasync function failOnLostMetadata(metadataFilePath: string, lastBuildFile: string) {\n const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;\n if (entries > 0) return;\n const last = await fs\n .readFile(lastBuildFile, \"utf8\")\n .then((content) => JSON.parse(content).entries as number)\n .catch(() => 0);\n if (last > 0) {\n throw new Error(\n `No translatable text was found, but the previous build had ${last} entries: the bundler served the files from its cache without the Weglot metadata. Delete ${path.relative(process.cwd(), path.dirname(path.dirname(lastBuildFile)))} and build again.`,\n );\n }\n}\n\nasync function writeLastBuild(metadataFilePath: string, lastBuildFile: string) {\n const entries = Object.keys(await loadMetadata(metadataFilePath, true)).length;\n await fs.mkdir(path.dirname(lastBuildFile), { recursive: true });\n await fs.writeFile(lastBuildFile, JSON.stringify({ entries }));\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 const distDir = path.resolve(nextConfig.distDir ?? \".next\");\n if (weglotConfig.environment !== \"development\") {\n // Kept with the bundler cache: files it serves are not compiled again, so\n // their entries must come from the previous build.\n weglotConfig.metadataDir = path.join(distDir, \"cache\", \"weglot\", \"metadata-build\");\n }\n const 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 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 const lastBuildFile = path.join(distDir, \"cache\", \"weglot\", \"last-build.json\");\n try {\n await pruneMetadata(metadataFilePath);\n await failOnLostMetadata(metadataFilePath, lastBuildFile);\n await processBuildTranslations({\n config: weglotConfig,\n publicOutputPath: distDir,\n metadataFilePath,\n });\n await addDictionariesToTraces(distDir, weglotConfig.targetLocales);\n await writeLastBuild(metadataFilePath, lastBuildFile);\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":";;;;;;;;;;;;;;;;AAiCA,SAAS,QAAQ,EACf,cACA,kBACA,wBAKsD;CACtD,MAAM,SAAS;EACb,YAAY,aAAa;EACzB,WAAW,aAAa;EACxB,cAAc,aAAa;EAE3B,SAAS,gBAAgB;EAC1B;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,aAAa,eACpB,EAAE,KAAK,CAAC,EAAE,SAAS,cAAc,EAAE,EAAE,SAAS,gBA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+CAA+C;EAE3D,MAAM,gBAAgB,KAAK,KAAKC,WAAS,SAAS,UAAU,kBAAkB;AAC9E,MAAI;AACF,SAAM,cAAc,iBAAiB;AACrC,SAAM,mBAAmB,kBAAkB,cAAc;AACzD,SAAM,yBAAyB;IAC7B,QAAQ;IACR,kBAAkBA;IAClB;IACD,CAAC;AACF,SAAM,wBAAwBA,WAAS,aAAa,cAAc;AAClE,SAAM,eAAe,kBAAkB,cAAc;WAC9C,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,6 +1,7 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_logger = require('../../utils/logger.cjs');
3
3
  const require_babel_compat = require('./babel-compat.cjs');
4
+ const require_msg = require('./msg.cjs');
4
5
  const require_process_file = require('./process-file.cjs');
5
6
  let path = require("path");
6
7
  path = require_rolldown_runtime.__toESM(path);
@@ -8,22 +9,35 @@ let _babel_parser = require("@babel/parser");
8
9
  _babel_parser = require_rolldown_runtime.__toESM(_babel_parser);
9
10
 
10
11
  //#region src/plugin/transform/index.ts
12
+ const JSX_FILE = /\.[jt]sx$/;
13
+ function parserPlugins(filePath) {
14
+ if (JSX_FILE.test(filePath)) return ["jsx", "typescript"];
15
+ if (/\.[cm]?ts$/.test(filePath)) return ["typescript"];
16
+ return ["jsx"];
17
+ }
11
18
  /**
12
19
  * Transform component code to inject translation calls
13
20
  */
14
21
  function transformComponent({ code, filePath, config }) {
22
+ const isJsxFile = JSX_FILE.test(filePath);
23
+ if (!isJsxFile && !require_msg.msgImportRegex.test(code)) return {
24
+ code,
25
+ newEntries: [],
26
+ transformed: false
27
+ };
15
28
  const relativeFilePath = path.default.relative(path.default.resolve(config.sourceRoot), filePath).split(path.default.sep).join("/");
16
29
  try {
17
30
  const ast = _babel_parser.parse(code, {
18
31
  sourceType: "module",
19
- plugins: ["jsx", "typescript"]
32
+ plugins: parserPlugins(filePath)
20
33
  });
21
34
  require_logger.logger.debug(`Transforming ${filePath}`);
22
- const translationEntries = require_process_file.processFile(ast, {
35
+ const translationEntries = isJsxFile ? require_process_file.processFile(ast, {
23
36
  relativeFilePath,
24
37
  needsDirective: config.useDirective,
25
38
  translatableAttributes: config.translatableAttributes
26
- });
39
+ }) : [];
40
+ if (require_msg.msgImportRegex.test(code)) translationEntries.push(...require_msg.processMsgCalls(ast, relativeFilePath));
27
41
  const output = require_babel_compat.generate(ast, { sourceMaps: true }, code);
28
42
  require_logger.logger.debug(`Transformed ${filePath}. Code: ${output.code}`);
29
43
  return {
@@ -1,26 +1,40 @@
1
1
  import { logger } from "../../utils/logger.mjs";
2
2
  import { generate } from "./babel-compat.mjs";
3
+ import { msgImportRegex, processMsgCalls } from "./msg.mjs";
3
4
  import { processFile } from "./process-file.mjs";
4
5
  import path from "path";
5
6
  import * as parser from "@babel/parser";
6
7
 
7
8
  //#region src/plugin/transform/index.ts
9
+ const JSX_FILE = /\.[jt]sx$/;
10
+ function parserPlugins(filePath) {
11
+ if (JSX_FILE.test(filePath)) return ["jsx", "typescript"];
12
+ if (/\.[cm]?ts$/.test(filePath)) return ["typescript"];
13
+ return ["jsx"];
14
+ }
8
15
  /**
9
16
  * Transform component code to inject translation calls
10
17
  */
11
18
  function transformComponent({ code, filePath, config }) {
19
+ const isJsxFile = JSX_FILE.test(filePath);
20
+ if (!isJsxFile && !msgImportRegex.test(code)) return {
21
+ code,
22
+ newEntries: [],
23
+ transformed: false
24
+ };
12
25
  const relativeFilePath = path.relative(path.resolve(config.sourceRoot), filePath).split(path.sep).join("/");
13
26
  try {
14
27
  const ast = parser.parse(code, {
15
28
  sourceType: "module",
16
- plugins: ["jsx", "typescript"]
29
+ plugins: parserPlugins(filePath)
17
30
  });
18
31
  logger.debug(`Transforming ${filePath}`);
19
- const translationEntries = processFile(ast, {
32
+ const translationEntries = isJsxFile ? processFile(ast, {
20
33
  relativeFilePath,
21
34
  needsDirective: config.useDirective,
22
35
  translatableAttributes: config.translatableAttributes
23
- });
36
+ }) : [];
37
+ if (msgImportRegex.test(code)) translationEntries.push(...processMsgCalls(ast, relativeFilePath));
24
38
  const output = generate(ast, { sourceMaps: true }, code);
25
39
  logger.debug(`Transformed ${filePath}. Code: ${output.code}`);
26
40
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/plugin/transform/index.ts"],"sourcesContent":["import * as parser from \"@babel/parser\";\nimport path from \"path\";\nimport type { WeglotConfig, TranslationEntry } from \"../../types\";\nimport { processFile } from \"./process-file\";\nimport { logger } from \"../../utils/logger\";\nimport { generate } from \"./babel-compat\";\n\nexport interface TransformResult {\n code: string;\n map?: any;\n newEntries?: TranslationEntry[];\n transformed: boolean;\n}\n\nexport interface BabelTransformOptions {\n code: string;\n filePath: string;\n config: WeglotConfig;\n}\n\n/**\n * Transform component code to inject translation calls\n */\nexport function transformComponent({\n code,\n filePath,\n config,\n}: BabelTransformOptions): TransformResult {\n // Get relative file path for consistent hashing\n const relativeFilePath = path\n .relative(path.resolve(config.sourceRoot), filePath)\n .split(path.sep)\n // '/' is used as a cross-platform path separator\n .join(\"/\");\n\n try {\n const ast = parser.parse(code, {\n sourceType: \"module\",\n plugins: [\"jsx\", \"typescript\"],\n });\n\n logger.debug(`Transforming ${filePath}`);\n\n const translationEntries = processFile(ast, {\n relativeFilePath,\n needsDirective: config.useDirective,\n translatableAttributes: config.translatableAttributes,\n });\n\n const output = generate(\n ast,\n {\n sourceMaps: true,\n },\n code,\n );\n\n logger.debug(`Transformed ${filePath}. Code: ${output.code}`);\n\n return {\n code: output.code,\n map: output.map,\n newEntries: translationEntries,\n transformed: translationEntries.length > 0,\n };\n } catch (error) {\n // TODO (AleksandrSl 08/12/2025): Should also log the message\n logger.error(`Failed to transform ${filePath}:`, error);\n // Return original code on error\n return {\n code,\n transformed: false,\n };\n }\n}\n"],"mappings":";;;;;;;;;;AAuBA,SAAgB,mBAAmB,EACjC,MACA,UACA,UACyC;CAEzC,MAAM,mBAAmB,KACtB,SAAS,KAAK,QAAQ,OAAO,WAAW,EAAE,SAAS,CACnD,MAAM,KAAK,IAAI,CAEf,KAAK,IAAI;AAEZ,KAAI;EACF,MAAM,MAAM,OAAO,MAAM,MAAM;GAC7B,YAAY;GACZ,SAAS,CAAC,OAAO,aAAa;GAC/B,CAAC;AAEF,SAAO,MAAM,gBAAgB,WAAW;EAExC,MAAM,qBAAqB,YAAY,KAAK;GAC1C;GACA,gBAAgB,OAAO;GACvB,wBAAwB,OAAO;GAChC,CAAC;EAEF,MAAM,SAAS,SACb,KACA,EACE,YAAY,MACb,EACD,KACD;AAED,SAAO,MAAM,eAAe,SAAS,UAAU,OAAO,OAAO;AAE7D,SAAO;GACL,MAAM,OAAO;GACb,KAAK,OAAO;GACZ,YAAY;GACZ,aAAa,mBAAmB,SAAS;GAC1C;UACM,OAAO;AAEd,SAAO,MAAM,uBAAuB,SAAS,IAAI,MAAM;AAEvD,SAAO;GACL;GACA,aAAa;GACd"}
1
+ {"version":3,"file":"index.mjs","names":["translationEntries: TranslationEntry[]"],"sources":["../../../src/plugin/transform/index.ts"],"sourcesContent":["import * as parser from \"@babel/parser\";\nimport path from \"path\";\nimport type { WeglotConfig, TranslationEntry } from \"../../types\";\nimport { processFile } from \"./process-file\";\nimport { msgImportRegex, processMsgCalls } from \"./msg\";\nimport { logger } from \"../../utils/logger\";\nimport { generate } from \"./babel-compat\";\n\nexport interface TransformResult {\n code: string;\n map?: any;\n newEntries?: TranslationEntry[];\n transformed: boolean;\n}\n\nexport interface BabelTransformOptions {\n code: string;\n filePath: string;\n config: WeglotConfig;\n}\n\nconst JSX_FILE = /\\.[jt]sx$/;\n\nfunction parserPlugins(filePath: string): parser.ParserPlugin[] {\n if (JSX_FILE.test(filePath)) return [\"jsx\", \"typescript\"];\n if (/\\.[cm]?ts$/.test(filePath)) return [\"typescript\"];\n return [\"jsx\"];\n}\n\n/**\n * Transform component code to inject translation calls\n */\nexport function transformComponent({\n code,\n filePath,\n config,\n}: BabelTransformOptions): TransformResult {\n const isJsxFile = JSX_FILE.test(filePath);\n if (!isJsxFile && !msgImportRegex.test(code)) {\n return { code, newEntries: [], transformed: false };\n }\n\n // Get relative file path for consistent hashing\n const relativeFilePath = path\n .relative(path.resolve(config.sourceRoot), filePath)\n .split(path.sep)\n // '/' is used as a cross-platform path separator\n .join(\"/\");\n\n try {\n const ast = parser.parse(code, {\n sourceType: \"module\",\n plugins: parserPlugins(filePath),\n });\n\n logger.debug(`Transforming ${filePath}`);\n\n const translationEntries: TranslationEntry[] = isJsxFile\n ? processFile(ast, {\n relativeFilePath,\n needsDirective: config.useDirective,\n translatableAttributes: config.translatableAttributes,\n })\n : [];\n if (msgImportRegex.test(code)) {\n translationEntries.push(...processMsgCalls(ast, relativeFilePath));\n }\n\n const output = generate(\n ast,\n {\n sourceMaps: true,\n },\n code,\n );\n\n logger.debug(`Transformed ${filePath}. Code: ${output.code}`);\n\n return {\n code: output.code,\n map: output.map,\n newEntries: translationEntries,\n transformed: translationEntries.length > 0,\n };\n } catch (error) {\n // TODO (AleksandrSl 08/12/2025): Should also log the message\n logger.error(`Failed to transform ${filePath}:`, error);\n // Return original code on error\n return {\n code,\n transformed: false,\n };\n }\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,WAAW;AAEjB,SAAS,cAAc,UAAyC;AAC9D,KAAI,SAAS,KAAK,SAAS,CAAE,QAAO,CAAC,OAAO,aAAa;AACzD,KAAI,aAAa,KAAK,SAAS,CAAE,QAAO,CAAC,aAAa;AACtD,QAAO,CAAC,MAAM;;;;;AAMhB,SAAgB,mBAAmB,EACjC,MACA,UACA,UACyC;CACzC,MAAM,YAAY,SAAS,KAAK,SAAS;AACzC,KAAI,CAAC,aAAa,CAAC,eAAe,KAAK,KAAK,CAC1C,QAAO;EAAE;EAAM,YAAY,EAAE;EAAE,aAAa;EAAO;CAIrD,MAAM,mBAAmB,KACtB,SAAS,KAAK,QAAQ,OAAO,WAAW,EAAE,SAAS,CACnD,MAAM,KAAK,IAAI,CAEf,KAAK,IAAI;AAEZ,KAAI;EACF,MAAM,MAAM,OAAO,MAAM,MAAM;GAC7B,YAAY;GACZ,SAAS,cAAc,SAAS;GACjC,CAAC;AAEF,SAAO,MAAM,gBAAgB,WAAW;EAExC,MAAMA,qBAAyC,YAC3C,YAAY,KAAK;GACf;GACA,gBAAgB,OAAO;GACvB,wBAAwB,OAAO;GAChC,CAAC,GACF,EAAE;AACN,MAAI,eAAe,KAAK,KAAK,CAC3B,oBAAmB,KAAK,GAAG,gBAAgB,KAAK,iBAAiB,CAAC;EAGpE,MAAM,SAAS,SACb,KACA,EACE,YAAY,MACb,EACD,KACD;AAED,SAAO,MAAM,eAAe,SAAS,UAAU,OAAO,OAAO;AAE7D,SAAO;GACL,MAAM,OAAO;GACb,KAAK,OAAO;GACZ,YAAY;GACZ,aAAa,mBAAmB,SAAS;GAC1C;UACM,OAAO;AAEd,SAAO,MAAM,uBAAuB,SAAS,IAAI,MAAM;AAEvD,SAAO;GACL;GACA,aAAa;GACd"}
@@ -0,0 +1,66 @@
1
+ const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
+ const require_logger = require('../../utils/logger.cjs');
3
+ const require_babel_compat = require('./babel-compat.cjs');
4
+ const require_utils = require('./utils.cjs');
5
+ const require_expression_strings = require('./expression-strings.cjs');
6
+ let _babel_types = require("@babel/types");
7
+ _babel_types = require_rolldown_runtime.__toESM(_babel_types);
8
+
9
+ //#region src/plugin/transform/msg.ts
10
+ const MSG_SOURCE = `${require_utils.root}/react`;
11
+ /** Quick pre-parse check that a file may import `msg`. */
12
+ const msgImportRegex = /@weglot\/translate-react\/react["']/;
13
+ function isMsgImport(path) {
14
+ const callee = path.node.callee;
15
+ if (!_babel_types.isIdentifier(callee)) return false;
16
+ const binding = path.scope.getBinding(callee.name);
17
+ if (!binding || binding.kind !== "module") return false;
18
+ const specifier = binding.path;
19
+ if (!specifier.isImportSpecifier()) return false;
20
+ const imported = specifier.node.imported;
21
+ const importedName = _babel_types.isIdentifier(imported) ? imported.name : imported.value;
22
+ const declaration = specifier.parentPath;
23
+ return importedName === "msg" && specifier.node.importKind !== "type" && declaration?.isImportDeclaration() === true && declaration.node.importKind !== "type" && declaration.node.source.value === MSG_SOURCE;
24
+ }
25
+ function readMessage(argument) {
26
+ if (_babel_types.isStringLiteral(argument)) return { text: argument.value };
27
+ if (!_babel_types.isTemplateLiteral(argument)) return null;
28
+ if (argument.expressions.length === 0) {
29
+ const quasi = argument.quasis[0];
30
+ return { text: quasi.value.cooked ?? quasi.value.raw };
31
+ }
32
+ const message = require_expression_strings.templateToMessage(argument);
33
+ if (!message) return null;
34
+ return {
35
+ text: message.text,
36
+ values: _babel_types.objectExpression([...message.variables.map((name) => _babel_types.objectProperty(_babel_types.identifier(name), _babel_types.identifier(name), false, true)), ...[...message.expressions].map(([name, expression]) => _babel_types.objectProperty(_babel_types.identifier(name), expression))])
37
+ };
38
+ }
39
+ /**
40
+ * Registers every `msg("…")` imported from the package and rewrites it to
41
+ * `msg("…", hash, values?)`, so the runtime descriptor carries its hash.
42
+ */
43
+ function processMsgCalls(ast, filePath) {
44
+ const entries = [];
45
+ require_babel_compat.traverse(ast, { CallExpression(path) {
46
+ if (path.node.arguments.length !== 1 || !isMsgImport(path)) return;
47
+ const argument = path.node.arguments[0];
48
+ const message = readMessage(argument);
49
+ if (!message || message.text.trim() === "") {
50
+ require_logger.logger.warn(`msg() in ${filePath} needs a string or template literal with text; it is left untranslated.`);
51
+ return;
52
+ }
53
+ const entry = require_utils.createTranslationEntry("message", message.text, {}, filePath, argument.loc?.start.line, argument.loc?.start.column);
54
+ entries.push(entry);
55
+ path.node.arguments = [
56
+ _babel_types.stringLiteral(message.text),
57
+ _babel_types.stringLiteral(entry.hash),
58
+ ...message.values ? [message.values] : []
59
+ ];
60
+ } });
61
+ return entries;
62
+ }
63
+
64
+ //#endregion
65
+ exports.msgImportRegex = msgImportRegex;
66
+ exports.processMsgCalls = processMsgCalls;
@@ -0,0 +1,64 @@
1
+ import { logger } from "../../utils/logger.mjs";
2
+ import { traverse } from "./babel-compat.mjs";
3
+ import { createTranslationEntry, root } from "./utils.mjs";
4
+ import { templateToMessage } from "./expression-strings.mjs";
5
+ import * as t from "@babel/types";
6
+
7
+ //#region src/plugin/transform/msg.ts
8
+ const MSG_SOURCE = `${root}/react`;
9
+ /** Quick pre-parse check that a file may import `msg`. */
10
+ const msgImportRegex = /@weglot\/translate-react\/react["']/;
11
+ function isMsgImport(path) {
12
+ const callee = path.node.callee;
13
+ if (!t.isIdentifier(callee)) return false;
14
+ const binding = path.scope.getBinding(callee.name);
15
+ if (!binding || binding.kind !== "module") return false;
16
+ const specifier = binding.path;
17
+ if (!specifier.isImportSpecifier()) return false;
18
+ const imported = specifier.node.imported;
19
+ const importedName = t.isIdentifier(imported) ? imported.name : imported.value;
20
+ const declaration = specifier.parentPath;
21
+ return importedName === "msg" && specifier.node.importKind !== "type" && declaration?.isImportDeclaration() === true && declaration.node.importKind !== "type" && declaration.node.source.value === MSG_SOURCE;
22
+ }
23
+ function readMessage(argument) {
24
+ if (t.isStringLiteral(argument)) return { text: argument.value };
25
+ if (!t.isTemplateLiteral(argument)) return null;
26
+ if (argument.expressions.length === 0) {
27
+ const quasi = argument.quasis[0];
28
+ return { text: quasi.value.cooked ?? quasi.value.raw };
29
+ }
30
+ const message = templateToMessage(argument);
31
+ if (!message) return null;
32
+ return {
33
+ text: message.text,
34
+ values: t.objectExpression([...message.variables.map((name) => t.objectProperty(t.identifier(name), t.identifier(name), false, true)), ...[...message.expressions].map(([name, expression]) => t.objectProperty(t.identifier(name), expression))])
35
+ };
36
+ }
37
+ /**
38
+ * Registers every `msg("…")` imported from the package and rewrites it to
39
+ * `msg("…", hash, values?)`, so the runtime descriptor carries its hash.
40
+ */
41
+ function processMsgCalls(ast, filePath) {
42
+ const entries = [];
43
+ traverse(ast, { CallExpression(path) {
44
+ if (path.node.arguments.length !== 1 || !isMsgImport(path)) return;
45
+ const argument = path.node.arguments[0];
46
+ const message = readMessage(argument);
47
+ if (!message || message.text.trim() === "") {
48
+ logger.warn(`msg() in ${filePath} needs a string or template literal with text; it is left untranslated.`);
49
+ return;
50
+ }
51
+ const entry = createTranslationEntry("message", message.text, {}, filePath, argument.loc?.start.line, argument.loc?.start.column);
52
+ entries.push(entry);
53
+ path.node.arguments = [
54
+ t.stringLiteral(message.text),
55
+ t.stringLiteral(entry.hash),
56
+ ...message.values ? [message.values] : []
57
+ ];
58
+ } });
59
+ return entries;
60
+ }
61
+
62
+ //#endregion
63
+ export { msgImportRegex, processMsgCalls };
64
+ //# sourceMappingURL=msg.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"msg.mjs","names":["entries: MessageTranslationEntry[]"],"sources":["../../../src/plugin/transform/msg.ts"],"sourcesContent":["import * as t from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\nimport type { MessageTranslationEntry } from \"../../types\";\nimport { logger } from \"../../utils/logger\";\nimport { traverse } from \"./babel-compat\";\nimport { templateToMessage } from \"./expression-strings\";\nimport { createTranslationEntry, root } from \"./utils\";\n\nexport const MSG_SOURCE = `${root}/react`;\n\n/** Quick pre-parse check that a file may import `msg`. */\nexport const msgImportRegex = /@weglot\\/translate-react\\/react[\"']/;\n\nfunction isMsgImport(path: NodePath<t.CallExpression>): boolean {\n const callee = path.node.callee;\n if (!t.isIdentifier(callee)) return false;\n\n const binding = path.scope.getBinding(callee.name);\n if (!binding || binding.kind !== \"module\") return false;\n\n const specifier = binding.path;\n if (!specifier.isImportSpecifier()) return false;\n\n const imported = specifier.node.imported;\n const importedName = t.isIdentifier(imported)\n ? imported.name\n : imported.value;\n const declaration = specifier.parentPath;\n\n return (\n importedName === \"msg\" &&\n specifier.node.importKind !== \"type\" &&\n declaration?.isImportDeclaration() === true &&\n declaration.node.importKind !== \"type\" &&\n declaration.node.source.value === MSG_SOURCE\n );\n}\n\nfunction readMessage(\n argument: t.Node,\n): { text: string; values?: t.ObjectExpression } | null {\n if (t.isStringLiteral(argument)) {\n return { text: argument.value };\n }\n\n if (!t.isTemplateLiteral(argument)) return null;\n\n if (argument.expressions.length === 0) {\n const quasi = argument.quasis[0];\n return { text: quasi.value.cooked ?? quasi.value.raw };\n }\n\n const message = templateToMessage(argument);\n if (!message) return null;\n\n return {\n text: message.text,\n values: t.objectExpression([\n ...message.variables.map((name) =>\n t.objectProperty(t.identifier(name), t.identifier(name), false, true),\n ),\n ...[...message.expressions].map(([name, expression]) =>\n t.objectProperty(t.identifier(name), expression),\n ),\n ]),\n };\n}\n\n/**\n * Registers every `msg(\"…\")` imported from the package and rewrites it to\n * `msg(\"…\", hash, values?)`, so the runtime descriptor carries its hash.\n */\nexport function processMsgCalls(\n ast: t.Node,\n filePath: string,\n): MessageTranslationEntry[] {\n const entries: MessageTranslationEntry[] = [];\n\n traverse(ast, {\n CallExpression(path) {\n if (path.node.arguments.length !== 1 || !isMsgImport(path)) return;\n\n const argument = path.node.arguments[0];\n const message = readMessage(argument);\n if (!message || message.text.trim() === \"\") {\n logger.warn(\n `msg() in ${filePath} needs a string or template literal with text; it is left untranslated.`,\n );\n return;\n }\n\n const entry = createTranslationEntry(\n \"message\",\n message.text,\n {},\n filePath,\n argument.loc?.start.line,\n argument.loc?.start.column,\n );\n entries.push(entry);\n\n path.node.arguments = [\n t.stringLiteral(message.text),\n t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EAAE,eAAe,EAAE,WAAW,KAAK,EAAE,WAAW,CACjD,CACF,CAAC;EACH;;;;;;AAOH,SAAgB,gBACd,KACA,UAC2B;CAC3B,MAAMA,UAAqC,EAAE;AAE7C,UAAS,KAAK,EACZ,eAAe,MAAM;AACnB,MAAI,KAAK,KAAK,UAAU,WAAW,KAAK,CAAC,YAAY,KAAK,CAAE;EAE5D,MAAM,WAAW,KAAK,KAAK,UAAU;EACrC,MAAM,UAAU,YAAY,SAAS;AACrC,MAAI,CAAC,WAAW,QAAQ,KAAK,MAAM,KAAK,IAAI;AAC1C,UAAO,KACL,YAAY,SAAS,yEACtB;AACD;;EAGF,MAAM,QAAQ,uBACZ,WACA,QAAQ,MACR,EAAE,EACF,UACA,SAAS,KAAK,MAAM,MACpB,SAAS,KAAK,MAAM,OACrB;AACD,UAAQ,KAAK,MAAM;AAEnB,OAAK,KAAK,YAAY;GACpB,EAAE,cAAc,QAAQ,KAAK;GAC7B,EAAE,cAAc,MAAM,KAAK;GAC3B,GAAI,QAAQ,SAAS,CAAC,QAAQ,OAAO,GAAG,EAAE;GAC3C;IAEJ,CAAC;AAEF,QAAO"}
@@ -1,10 +1,10 @@
1
1
  const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
2
  const require_logger = require('../../utils/logger.cjs');
3
3
  const require_engine = require('../../translators/weglot/engine.cjs');
4
- const require_utils = require('./utils.cjs');
5
- const require_metadata = require('./metadata.cjs');
6
4
  const require_babel_compat = require('./babel-compat.cjs');
5
+ const require_utils = require('./utils.cjs');
7
6
  const require_expression_strings = require('./expression-strings.cjs');
7
+ const require_metadata = require('./metadata.cjs');
8
8
  let _babel_types = require("@babel/types");
9
9
  _babel_types = require_rolldown_runtime.__toESM(_babel_types);
10
10
 
@@ -239,10 +239,9 @@ function hasMergeableSiblings(children) {
239
239
  /**
240
240
  * Serialize JSX children to a translation string with placeholders
241
241
  */
242
- function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ new Map()) {
242
+ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ new Map(), expressions = /* @__PURE__ */ new Map()) {
243
243
  let text = "";
244
244
  const variables = [];
245
- const expressions = /* @__PURE__ */ new Map();
246
245
  const components = /* @__PURE__ */ new Map();
247
246
  for (const child of children) if (child.type === "JSXText") {
248
247
  let normalized = require_utils.normalizeWhitespace(child.value);
@@ -276,7 +275,7 @@ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ n
276
275
  const tagName = `${elementName}${count}`;
277
276
  translateAttributes(child, state);
278
277
  if (shouldTranslate) {
279
- const nested = serializeJSXChildren(child.children, state, elementCounts);
278
+ const nested = serializeJSXChildren(child.children, state, elementCounts, expressions);
280
279
  text += `<${tagName}>${nested.text}</${tagName}>`;
281
280
  for (const v of nested.variables) if (!variables.includes(v)) variables.push(v);
282
281
  for (const [nestedTag, nestedElement] of nested.components) components.set(nestedTag, nestedElement);
@@ -299,7 +298,16 @@ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ n
299
298
  function transformVoidElement(node, state) {
300
299
  translateAttributes(node, state);
301
300
  }
301
+ /** Digits, punctuation and placeholders alone come back from the API unchanged. */
302
+ function hasWords(children) {
303
+ return children.some((child) => {
304
+ if (child.type === "JSXText") return /\p{L}/u.test(child.value);
305
+ if (child.type === "JSXExpressionContainer") return child.expression.type === "StringLiteral" && /\p{L}/u.test(child.expression.value);
306
+ return child.type === "JSXElement" && !require_utils.isVoidElement(child) && !shouldSkipTranslationForElement(child) && hasWords(child.children);
307
+ });
308
+ }
302
309
  function getTranslationScope(node, state) {
310
+ if (!hasWords(node.children)) return null;
303
311
  if (hasMixedContent(node)) {
304
312
  const serialized = serializeJSXChildren(node.children, state);
305
313
  const text$1 = serialized.text.trim();
@@ -394,13 +402,16 @@ function injectTranslationHook(path, component, state) {
394
402
  state.needsUnifiedImport = true;
395
403
  }
396
404
  }
405
+ function importsBinding(programPath, name, source) {
406
+ return programPath.node.body.some((statement) => _babel_types.isImportDeclaration(statement) && statement.importKind !== "type" && statement.source.value === source && statement.specifiers.some((specifier) => _babel_types.isImportSpecifier(specifier) && specifier.local.name === name && _babel_types.isIdentifier(specifier.imported, { name }) && specifier.importKind !== "type"));
407
+ }
397
408
  /**
398
409
  * Add translation imports at the top of the file
399
410
  * Called on Program exit after all components have been processed
400
411
  */
401
412
  function addTranslationImports(programPath, state) {
402
- if (state.needsAsyncImport) programPath.node.body.unshift(require_utils.constructServerImport());
403
- if (state.needsUnifiedImport) programPath.node.body.unshift(require_utils.comstructUnifiedImport());
413
+ if (state.needsAsyncImport && !importsBinding(programPath, "getServerTranslations", require_utils.constructServerImport().source.value)) programPath.node.body.unshift(require_utils.constructServerImport());
414
+ if (state.needsUnifiedImport && !importsBinding(programPath, "useTranslation", require_utils.comstructUnifiedImport().source.value)) programPath.node.body.unshift(require_utils.comstructUnifiedImport());
404
415
  }
405
416
  /**
406
417
  * Handle component function detection and state update
@@ -1,9 +1,9 @@
1
1
  import { logger } from "../../utils/logger.mjs";
2
2
  import { INLINE_TAGS } from "../../translators/weglot/engine.mjs";
3
- import { DEFAULT_TRANSLATOR, buildTranslationCall, comstructUnifiedImport, constructServerImport, constructTranslationCall, createTranslationEntry, escapeTextForICU, hasUseI18nDirective, inferComponentName, injectServerHook, injectUnifiedHook, isComponentName, isNestedComponent, isReactComponent, isVoidElement, normalizeWhitespace, translatorNameFor } from "./utils.mjs";
4
- import { processNextDynamicMetadata, processNextStaticMetadata } from "./metadata.mjs";
5
3
  import { traverse } from "./babel-compat.mjs";
4
+ import { DEFAULT_TRANSLATOR, buildTranslationCall, comstructUnifiedImport, constructServerImport, constructTranslationCall, createTranslationEntry, escapeTextForICU, hasUseI18nDirective, inferComponentName, injectServerHook, injectUnifiedHook, isComponentName, isNestedComponent, isReactComponent, isVoidElement, normalizeWhitespace, translatorNameFor } from "./utils.mjs";
6
5
  import { collectConstantReferences, collectLiteralPaths, isTranslatablePosition, isTranslatableText, templateToMessage } from "./expression-strings.mjs";
6
+ import { processNextDynamicMetadata, processNextStaticMetadata } from "./metadata.mjs";
7
7
  import * as t from "@babel/types";
8
8
 
9
9
  //#region src/plugin/transform/process-file.ts
@@ -237,10 +237,9 @@ function hasMergeableSiblings(children) {
237
237
  /**
238
238
  * Serialize JSX children to a translation string with placeholders
239
239
  */
240
- function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ new Map()) {
240
+ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ new Map(), expressions = /* @__PURE__ */ new Map()) {
241
241
  let text = "";
242
242
  const variables = [];
243
- const expressions = /* @__PURE__ */ new Map();
244
243
  const components = /* @__PURE__ */ new Map();
245
244
  for (const child of children) if (child.type === "JSXText") {
246
245
  let normalized = normalizeWhitespace(child.value);
@@ -274,7 +273,7 @@ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ n
274
273
  const tagName = `${elementName}${count}`;
275
274
  translateAttributes(child, state);
276
275
  if (shouldTranslate) {
277
- const nested = serializeJSXChildren(child.children, state, elementCounts);
276
+ const nested = serializeJSXChildren(child.children, state, elementCounts, expressions);
278
277
  text += `<${tagName}>${nested.text}</${tagName}>`;
279
278
  for (const v of nested.variables) if (!variables.includes(v)) variables.push(v);
280
279
  for (const [nestedTag, nestedElement] of nested.components) components.set(nestedTag, nestedElement);
@@ -297,7 +296,16 @@ function serializeJSXChildren(children, state, elementCounts = /* @__PURE__ */ n
297
296
  function transformVoidElement(node, state) {
298
297
  translateAttributes(node, state);
299
298
  }
299
+ /** Digits, punctuation and placeholders alone come back from the API unchanged. */
300
+ function hasWords(children) {
301
+ return children.some((child) => {
302
+ if (child.type === "JSXText") return /\p{L}/u.test(child.value);
303
+ if (child.type === "JSXExpressionContainer") return child.expression.type === "StringLiteral" && /\p{L}/u.test(child.expression.value);
304
+ return child.type === "JSXElement" && !isVoidElement(child) && !shouldSkipTranslationForElement(child) && hasWords(child.children);
305
+ });
306
+ }
300
307
  function getTranslationScope(node, state) {
308
+ if (!hasWords(node.children)) return null;
301
309
  if (hasMixedContent(node)) {
302
310
  const serialized = serializeJSXChildren(node.children, state);
303
311
  const text$1 = serialized.text.trim();
@@ -392,13 +400,16 @@ function injectTranslationHook(path, component, state) {
392
400
  state.needsUnifiedImport = true;
393
401
  }
394
402
  }
403
+ function importsBinding(programPath, name, source) {
404
+ return programPath.node.body.some((statement) => t.isImportDeclaration(statement) && statement.importKind !== "type" && statement.source.value === source && statement.specifiers.some((specifier) => t.isImportSpecifier(specifier) && specifier.local.name === name && t.isIdentifier(specifier.imported, { name }) && specifier.importKind !== "type"));
405
+ }
395
406
  /**
396
407
  * Add translation imports at the top of the file
397
408
  * Called on Program exit after all components have been processed
398
409
  */
399
410
  function addTranslationImports(programPath, state) {
400
- if (state.needsAsyncImport) programPath.node.body.unshift(constructServerImport());
401
- if (state.needsUnifiedImport) programPath.node.body.unshift(comstructUnifiedImport());
411
+ if (state.needsAsyncImport && !importsBinding(programPath, "getServerTranslations", constructServerImport().source.value)) programPath.node.body.unshift(constructServerImport());
412
+ if (state.needsUnifiedImport && !importsBinding(programPath, "useTranslation", comstructUnifiedImport().source.value)) programPath.node.body.unshift(comstructUnifiedImport());
402
413
  }
403
414
  /**
404
415
  * Handle component function detection and state update