@weglot/translate-react 0.0.0-stage → 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.
Files changed (292) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +6 -0
  3. package/README.md +199 -2
  4. package/build/_virtual/rolldown_runtime.cjs +29 -0
  5. package/build/_virtual/rolldown_runtime.mjs +7 -0
  6. package/build/index.cjs +0 -0
  7. package/build/index.d.cts +2 -0
  8. package/build/index.d.mts +2 -0
  9. package/build/index.mjs +1 -0
  10. package/build/locale.d.cts +6 -0
  11. package/build/locale.d.cts.map +1 -0
  12. package/build/locale.d.mts +6 -0
  13. package/build/locale.d.mts.map +1 -0
  14. package/build/metadata/manager.cjs +119 -0
  15. package/build/metadata/manager.mjs +114 -0
  16. package/build/metadata/manager.mjs.map +1 -0
  17. package/build/plugin/build-translator.cjs +210 -0
  18. package/build/plugin/build-translator.mjs +208 -0
  19. package/build/plugin/build-translator.mjs.map +1 -0
  20. package/build/plugin/cleanup.cjs +20 -0
  21. package/build/plugin/cleanup.mjs +20 -0
  22. package/build/plugin/cleanup.mjs.map +1 -0
  23. package/build/plugin/index.cjs +0 -0
  24. package/build/plugin/index.d.cts +2 -0
  25. package/build/plugin/index.d.mts +2 -0
  26. package/build/plugin/index.mjs +1 -0
  27. package/build/plugin/next-compiler-loader.cjs +40 -0
  28. package/build/plugin/next-compiler-loader.d.cts +12 -0
  29. package/build/plugin/next-compiler-loader.d.cts.map +1 -0
  30. package/build/plugin/next-compiler-loader.d.mts +13 -0
  31. package/build/plugin/next-compiler-loader.d.mts.map +1 -0
  32. package/build/plugin/next-compiler-loader.mjs +41 -0
  33. package/build/plugin/next-compiler-loader.mjs.map +1 -0
  34. package/build/plugin/next-config-loader.cjs +13 -0
  35. package/build/plugin/next-config-loader.d.cts +8 -0
  36. package/build/plugin/next-config-loader.d.cts.map +1 -0
  37. package/build/plugin/next-config-loader.d.mts +9 -0
  38. package/build/plugin/next-config-loader.d.mts.map +1 -0
  39. package/build/plugin/next-config-loader.mjs +14 -0
  40. package/build/plugin/next-config-loader.mjs.map +1 -0
  41. package/build/plugin/next-locale-client-loader.cjs +9 -0
  42. package/build/plugin/next-locale-client-loader.d.cts +8 -0
  43. package/build/plugin/next-locale-client-loader.d.cts.map +1 -0
  44. package/build/plugin/next-locale-client-loader.d.mts +9 -0
  45. package/build/plugin/next-locale-client-loader.d.mts.map +1 -0
  46. package/build/plugin/next-locale-client-loader.mjs +10 -0
  47. package/build/plugin/next-locale-client-loader.mjs.map +1 -0
  48. package/build/plugin/next-locale-server-loader.cjs +9 -0
  49. package/build/plugin/next-locale-server-loader.d.cts +8 -0
  50. package/build/plugin/next-locale-server-loader.d.cts.map +1 -0
  51. package/build/plugin/next-locale-server-loader.d.mts +9 -0
  52. package/build/plugin/next-locale-server-loader.d.mts.map +1 -0
  53. package/build/plugin/next-locale-server-loader.mjs +10 -0
  54. package/build/plugin/next-locale-server-loader.mjs.map +1 -0
  55. package/build/plugin/next.cjs +227 -0
  56. package/build/plugin/next.d.cts +9 -0
  57. package/build/plugin/next.d.cts.map +1 -0
  58. package/build/plugin/next.d.mts +9 -0
  59. package/build/plugin/next.d.mts.map +1 -0
  60. package/build/plugin/next.mjs +229 -0
  61. package/build/plugin/next.mjs.map +1 -0
  62. package/build/plugin/transform/babel-compat.cjs +13 -0
  63. package/build/plugin/transform/babel-compat.mjs +10 -0
  64. package/build/plugin/transform/babel-compat.mjs.map +1 -0
  65. package/build/plugin/transform/expression-strings.cjs +145 -0
  66. package/build/plugin/transform/expression-strings.mjs +140 -0
  67. package/build/plugin/transform/expression-strings.mjs.map +1 -0
  68. package/build/plugin/transform/index.cjs +45 -0
  69. package/build/plugin/transform/index.mjs +43 -0
  70. package/build/plugin/transform/index.mjs.map +1 -0
  71. package/build/plugin/transform/metadata.cjs +142 -0
  72. package/build/plugin/transform/metadata.mjs +141 -0
  73. package/build/plugin/transform/metadata.mjs.map +1 -0
  74. package/build/plugin/transform/process-file.cjs +525 -0
  75. package/build/plugin/transform/process-file.mjs +524 -0
  76. package/build/plugin/transform/process-file.mjs.map +1 -0
  77. package/build/plugin/transform/use-i18n.cjs +8 -0
  78. package/build/plugin/transform/use-i18n.mjs +7 -0
  79. package/build/plugin/transform/use-i18n.mjs.map +1 -0
  80. package/build/plugin/transform/utils.cjs +237 -0
  81. package/build/plugin/transform/utils.mjs +219 -0
  82. package/build/plugin/transform/utils.mjs.map +1 -0
  83. package/build/plugin/unplugin.cjs +188 -0
  84. package/build/plugin/unplugin.d.cts +8 -0
  85. package/build/plugin/unplugin.d.cts.map +1 -0
  86. package/build/plugin/unplugin.d.mts +8 -0
  87. package/build/plugin/unplugin.d.mts.map +1 -0
  88. package/build/plugin/unplugin.mjs +188 -0
  89. package/build/plugin/unplugin.mjs.map +1 -0
  90. package/build/plugin/vite.cjs +27 -0
  91. package/build/plugin/vite.d.cts +9 -0
  92. package/build/plugin/vite.d.cts.map +1 -0
  93. package/build/plugin/vite.d.mts +9 -0
  94. package/build/plugin/vite.d.mts.map +1 -0
  95. package/build/plugin/vite.mjs +28 -0
  96. package/build/plugin/vite.mjs.map +1 -0
  97. package/build/plugin/webpack.cjs +26 -0
  98. package/build/plugin/webpack.d.cts +8 -0
  99. package/build/plugin/webpack.d.cts.map +1 -0
  100. package/build/plugin/webpack.d.mts +8 -0
  101. package/build/plugin/webpack.d.mts.map +1 -0
  102. package/build/plugin/webpack.mjs +27 -0
  103. package/build/plugin/webpack.mjs.map +1 -0
  104. package/build/react/client/index.cjs +9 -0
  105. package/build/react/client/index.d.cts +5 -0
  106. package/build/react/client/index.d.mts +5 -0
  107. package/build/react/client/index.mjs +6 -0
  108. package/build/react/client/useTranslation.cjs +71 -0
  109. package/build/react/client/useTranslation.d.cts +42 -0
  110. package/build/react/client/useTranslation.d.cts.map +1 -0
  111. package/build/react/client/useTranslation.d.mts +42 -0
  112. package/build/react/client/useTranslation.d.mts.map +1 -0
  113. package/build/react/client/useTranslation.mjs +71 -0
  114. package/build/react/client/useTranslation.mjs.map +1 -0
  115. package/build/react/next/client.cjs +25 -0
  116. package/build/react/next/client.d.cts +9 -0
  117. package/build/react/next/client.d.cts.map +1 -0
  118. package/build/react/next/client.d.mts +9 -0
  119. package/build/react/next/client.d.mts.map +1 -0
  120. package/build/react/next/client.mjs +24 -0
  121. package/build/react/next/client.mjs.map +1 -0
  122. package/build/react/next/cookie-locale-resolver.cjs +29 -0
  123. package/build/react/next/cookie-locale-resolver.d.cts +33 -0
  124. package/build/react/next/cookie-locale-resolver.d.cts.map +1 -0
  125. package/build/react/next/cookie-locale-resolver.d.mts +33 -0
  126. package/build/react/next/cookie-locale-resolver.d.mts.map +1 -0
  127. package/build/react/next/cookie-locale-resolver.mjs +29 -0
  128. package/build/react/next/cookie-locale-resolver.mjs.map +1 -0
  129. package/build/react/next/server.cjs +21 -0
  130. package/build/react/next/server.d.cts +13 -0
  131. package/build/react/next/server.d.cts.map +1 -0
  132. package/build/react/next/server.d.mts +14 -0
  133. package/build/react/next/server.d.mts.map +1 -0
  134. package/build/react/next/server.mjs +20 -0
  135. package/build/react/next/server.mjs.map +1 -0
  136. package/build/react/server/ServerWeglotProvider.cjs +19 -0
  137. package/build/react/server/ServerWeglotProvider.d.cts +12 -0
  138. package/build/react/server/ServerWeglotProvider.d.cts.map +1 -0
  139. package/build/react/server/ServerWeglotProvider.d.mts +12 -0
  140. package/build/react/server/ServerWeglotProvider.d.mts.map +1 -0
  141. package/build/react/server/ServerWeglotProvider.mjs +19 -0
  142. package/build/react/server/ServerWeglotProvider.mjs.map +1 -0
  143. package/build/react/server/index.cjs +7 -0
  144. package/build/react/server/index.d.cts +4 -0
  145. package/build/react/server/index.d.mts +4 -0
  146. package/build/react/server/index.mjs +5 -0
  147. package/build/react/server/useTranslation.cjs +60 -0
  148. package/build/react/server/useTranslation.d.cts +36 -0
  149. package/build/react/server/useTranslation.d.cts.map +1 -0
  150. package/build/react/server/useTranslation.d.mts +36 -0
  151. package/build/react/server/useTranslation.d.mts.map +1 -0
  152. package/build/react/server/useTranslation.mjs +60 -0
  153. package/build/react/server/useTranslation.mjs.map +1 -0
  154. package/build/react/server-only/index.cjs +42 -0
  155. package/build/react/server-only/index.d.cts +38 -0
  156. package/build/react/server-only/index.d.cts.map +1 -0
  157. package/build/react/server-only/index.d.mts +38 -0
  158. package/build/react/server-only/index.d.mts.map +1 -0
  159. package/build/react/server-only/index.mjs +42 -0
  160. package/build/react/server-only/index.mjs.map +1 -0
  161. package/build/react/server-only/translations.cjs +86 -0
  162. package/build/react/server-only/translations.mjs +86 -0
  163. package/build/react/server-only/translations.mjs.map +1 -0
  164. package/build/react/shared/LocaleSwitcher.cjs +61 -0
  165. package/build/react/shared/LocaleSwitcher.d.cts +71 -0
  166. package/build/react/shared/LocaleSwitcher.d.cts.map +1 -0
  167. package/build/react/shared/LocaleSwitcher.d.mts +71 -0
  168. package/build/react/shared/LocaleSwitcher.d.mts.map +1 -0
  169. package/build/react/shared/LocaleSwitcher.mjs +61 -0
  170. package/build/react/shared/LocaleSwitcher.mjs.map +1 -0
  171. package/build/react/shared/WeglotContext.cjs +14 -0
  172. package/build/react/shared/WeglotContext.d.cts +34 -0
  173. package/build/react/shared/WeglotContext.d.cts.map +1 -0
  174. package/build/react/shared/WeglotContext.d.mts +34 -0
  175. package/build/react/shared/WeglotContext.d.mts.map +1 -0
  176. package/build/react/shared/WeglotContext.mjs +13 -0
  177. package/build/react/shared/WeglotContext.mjs.map +1 -0
  178. package/build/react/shared/WeglotProvider.cjs +250 -0
  179. package/build/react/shared/WeglotProvider.d.cts +60 -0
  180. package/build/react/shared/WeglotProvider.d.cts.map +1 -0
  181. package/build/react/shared/WeglotProvider.d.mts +60 -0
  182. package/build/react/shared/WeglotProvider.d.mts.map +1 -0
  183. package/build/react/shared/WeglotProvider.mjs +250 -0
  184. package/build/react/shared/WeglotProvider.mjs.map +1 -0
  185. package/build/react/shared/render-rich-text.cjs +56 -0
  186. package/build/react/shared/render-rich-text.d.cts +16 -0
  187. package/build/react/shared/render-rich-text.d.cts.map +1 -0
  188. package/build/react/shared/render-rich-text.d.mts +16 -0
  189. package/build/react/shared/render-rich-text.d.mts.map +1 -0
  190. package/build/react/shared/render-rich-text.mjs +55 -0
  191. package/build/react/shared/render-rich-text.mjs.map +1 -0
  192. package/build/react/shared/utils.cjs +34 -0
  193. package/build/react/shared/utils.mjs +35 -0
  194. package/build/react/shared/utils.mjs.map +1 -0
  195. package/build/react/types.d.cts +16 -0
  196. package/build/react/types.d.cts.map +1 -0
  197. package/build/react/types.d.mts +16 -0
  198. package/build/react/types.d.mts.map +1 -0
  199. package/build/runtime/html/segmenter.cjs +226 -0
  200. package/build/runtime/html/segmenter.mjs +225 -0
  201. package/build/runtime/html/segmenter.mjs.map +1 -0
  202. package/build/runtime/index.cjs +6 -0
  203. package/build/runtime/index.d.cts +2 -0
  204. package/build/runtime/index.d.mts +2 -0
  205. package/build/runtime/index.mjs +3 -0
  206. package/build/runtime/translate-dynamic.cjs +144 -0
  207. package/build/runtime/translate-dynamic.d.cts +29 -0
  208. package/build/runtime/translate-dynamic.d.cts.map +1 -0
  209. package/build/runtime/translate-dynamic.d.mts +29 -0
  210. package/build/runtime/translate-dynamic.d.mts.map +1 -0
  211. package/build/runtime/translate-dynamic.mjs +141 -0
  212. package/build/runtime/translate-dynamic.mjs.map +1 -0
  213. package/build/translation-server/logger.cjs +37 -0
  214. package/build/translation-server/logger.mjs +37 -0
  215. package/build/translation-server/logger.mjs.map +1 -0
  216. package/build/translation-server/translation-server.cjs +451 -0
  217. package/build/translation-server/translation-server.mjs +448 -0
  218. package/build/translation-server/translation-server.mjs.map +1 -0
  219. package/build/translators/api.cjs +12 -0
  220. package/build/translators/api.mjs +12 -0
  221. package/build/translators/api.mjs.map +1 -0
  222. package/build/translators/cache-factory.cjs +26 -0
  223. package/build/translators/cache-factory.mjs +27 -0
  224. package/build/translators/cache-factory.mjs.map +1 -0
  225. package/build/translators/local-cache.cjs +132 -0
  226. package/build/translators/local-cache.mjs +130 -0
  227. package/build/translators/local-cache.mjs.map +1 -0
  228. package/build/translators/translation-service.cjs +139 -0
  229. package/build/translators/translation-service.mjs +140 -0
  230. package/build/translators/translation-service.mjs.map +1 -0
  231. package/build/translators/weglot/api-client.cjs +131 -0
  232. package/build/translators/weglot/api-client.mjs +130 -0
  233. package/build/translators/weglot/api-client.mjs.map +1 -0
  234. package/build/translators/weglot/definitions/definitions.generated.cjs +53 -0
  235. package/build/translators/weglot/definitions/definitions.generated.mjs +52 -0
  236. package/build/translators/weglot/definitions/definitions.generated.mjs.map +1 -0
  237. package/build/translators/weglot/engine.cjs +43 -0
  238. package/build/translators/weglot/engine.mjs +40 -0
  239. package/build/translators/weglot/engine.mjs.map +1 -0
  240. package/build/translators/weglot/translator.cjs +67 -0
  241. package/build/translators/weglot/translator.mjs +68 -0
  242. package/build/translators/weglot/translator.mjs.map +1 -0
  243. package/build/translators/weglot/wire-format.cjs +128 -0
  244. package/build/translators/weglot/wire-format.mjs +129 -0
  245. package/build/translators/weglot/wire-format.mjs.map +1 -0
  246. package/build/types.d.cts +153 -0
  247. package/build/types.d.cts.map +1 -0
  248. package/build/types.d.mts +153 -0
  249. package/build/types.d.mts.map +1 -0
  250. package/build/utils/config-factory.cjs +100 -0
  251. package/build/utils/config-factory.mjs +97 -0
  252. package/build/utils/config-factory.mjs.map +1 -0
  253. package/build/utils/hash.cjs +17 -0
  254. package/build/utils/hash.mjs +16 -0
  255. package/build/utils/hash.mjs.map +1 -0
  256. package/build/utils/is-valid-locale.cjs +13 -0
  257. package/build/utils/is-valid-locale.mjs +13 -0
  258. package/build/utils/is-valid-locale.mjs.map +1 -0
  259. package/build/utils/logger.cjs +51 -0
  260. package/build/utils/logger.mjs +50 -0
  261. package/build/utils/logger.mjs.map +1 -0
  262. package/build/utils/path-helpers.cjs +49 -0
  263. package/build/utils/path-helpers.mjs +47 -0
  264. package/build/utils/path-helpers.mjs.map +1 -0
  265. package/build/utils/timeout.cjs +42 -0
  266. package/build/utils/timeout.mjs +41 -0
  267. package/build/utils/timeout.mjs.map +1 -0
  268. package/build/virtual/code-generator.cjs +58 -0
  269. package/build/virtual/code-generator.mjs +57 -0
  270. package/build/virtual/code-generator.mjs.map +1 -0
  271. package/build/virtual/config.cjs +19 -0
  272. package/build/virtual/config.d.cts +15 -0
  273. package/build/virtual/config.d.cts.map +1 -0
  274. package/build/virtual/config.d.mts +15 -0
  275. package/build/virtual/config.d.mts.map +1 -0
  276. package/build/virtual/config.mjs +14 -0
  277. package/build/virtual/config.mjs.map +1 -0
  278. package/build/virtual/locale/client.cjs +23 -0
  279. package/build/virtual/locale/client.d.cts +19 -0
  280. package/build/virtual/locale/client.d.cts.map +1 -0
  281. package/build/virtual/locale/client.d.mts +19 -0
  282. package/build/virtual/locale/client.d.mts.map +1 -0
  283. package/build/virtual/locale/client.mjs +22 -0
  284. package/build/virtual/locale/client.mjs.map +1 -0
  285. package/build/virtual/locale/server.cjs +13 -0
  286. package/build/virtual/locale/server.d.cts +13 -0
  287. package/build/virtual/locale/server.d.cts.map +1 -0
  288. package/build/virtual/locale/server.d.mts +13 -0
  289. package/build/virtual/locale/server.d.mts.map +1 -0
  290. package/build/virtual/locale/server.mjs +13 -0
  291. package/build/virtual/locale/server.mjs.map +1 -0
  292. package/package.json +260 -4
@@ -0,0 +1,451 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_logger = require('./logger.cjs');
3
+ const require_translation_service = require('../translators/translation-service.cjs');
4
+ const require_manager = require('../metadata/manager.cjs');
5
+ const require_is_valid_locale = require('../utils/is-valid-locale.cjs');
6
+ let http = require("http");
7
+ http = require_rolldown_runtime.__toESM(http);
8
+ let crypto = require("crypto");
9
+ crypto = require_rolldown_runtime.__toESM(crypto);
10
+ let url = require("url");
11
+
12
+ //#region src/translation-server/translation-server.ts
13
+ /**
14
+ * Simple HTTP server for serving translations during development
15
+ *
16
+ * This server:
17
+ * - Finds a free port automatically
18
+ * - Serves translations via:
19
+ * - GET /translations/:locale - Full dictionary (cached)
20
+ * - POST /translations/:locale (body: { hashes: string[] }) - Batch translation
21
+ * - Uses the same translation logic as middleware
22
+ * - Can be started/stopped programmatically
23
+ */
24
+ var TranslationServer = class {
25
+ server = null;
26
+ url = void 0;
27
+ logger;
28
+ config;
29
+ configHash;
30
+ startPort;
31
+ onReadyCallback;
32
+ onErrorCallback;
33
+ metadata = null;
34
+ connections = /* @__PURE__ */ new Set();
35
+ translationService;
36
+ constructor(options) {
37
+ this.config = options.config;
38
+ this.configHash = hashConfig(options.config);
39
+ this.translationService = options.translationService ?? new require_translation_service.TranslationService(options.config, require_logger.getLogger(options.config));
40
+ this.startPort = options.config.dev.translationServerStartPort;
41
+ this.onReadyCallback = options.onReady;
42
+ this.onErrorCallback = options.onError;
43
+ this.logger = require_logger.getLogger(this.config);
44
+ }
45
+ /**
46
+ * Start the server and find an available port
47
+ */
48
+ async start() {
49
+ if (this.server) throw new Error("Server is already running");
50
+ this.logger.info(`🔧 Initializing translator...`);
51
+ const port = await this.findAvailablePort(this.startPort);
52
+ return new Promise((resolve, reject) => {
53
+ this.server = http.default.createServer((req, res) => {
54
+ this.logger.info(`📥 Received: ${req.method} ${req.url}`);
55
+ this.handleRequest(req, res).catch((error) => {
56
+ this.logger.error(`Request handler error:`, error);
57
+ this.logger.error(error.stack);
58
+ if (!res.headersSent) {
59
+ res.writeHead(500, { "Content-Type": "application/json" });
60
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
61
+ }
62
+ });
63
+ });
64
+ this.logger.debug(`Starting translation server on port ${port}`);
65
+ this.server.on("connection", (socket) => {
66
+ this.connections.add(socket);
67
+ socket.once("close", () => {
68
+ this.connections.delete(socket);
69
+ });
70
+ });
71
+ this.server.on("error", (error) => {
72
+ if (error.code === "EADDRINUSE") reject(/* @__PURE__ */ new Error(`Port ${port} is already in use`));
73
+ else {
74
+ this.logger.error(`Translation server error: ${error.message}\n`);
75
+ this.onErrorCallback?.(error);
76
+ reject(error);
77
+ }
78
+ });
79
+ this.server.listen(port, "127.0.0.1", () => {
80
+ this.url = `http://127.0.0.1:${port}`;
81
+ this.logger.info(`Translation server listening on ${this.url}`);
82
+ this.onReadyCallback?.(port);
83
+ resolve(port);
84
+ });
85
+ });
86
+ }
87
+ /**
88
+ * Stop the server
89
+ */
90
+ async stop() {
91
+ if (!this.server) {
92
+ this.logger.debug("Translation server is not running. Nothing to stop.");
93
+ return;
94
+ }
95
+ for (const socket of this.connections) socket.destroy();
96
+ this.connections.clear();
97
+ return new Promise((resolve, reject) => {
98
+ this.server.close((error) => {
99
+ if (error) reject(error);
100
+ else {
101
+ this.logger.info(`Translation server stopped`);
102
+ this.server = null;
103
+ this.url = void 0;
104
+ resolve();
105
+ }
106
+ });
107
+ });
108
+ }
109
+ /**
110
+ * Get the current port (null if not running)
111
+ */
112
+ getUrl() {
113
+ return this.url;
114
+ }
115
+ /**
116
+ * Start a new server or get the URL of an existing one on the preferred port.
117
+ *
118
+ * This method optimizes for the common case where a translation server is already
119
+ * running on a preferred port. If that port is taken, it checks if it's our service
120
+ * by calling the health check endpoint. If it is, we reuse it instead of starting
121
+ * a new server on a different port.
122
+ *
123
+ * @returns URL of the running server (new or existing)
124
+ */
125
+ async startOrGetUrl() {
126
+ if (this.server && this.url) {
127
+ this.logger.info(`Using existing server instance at ${this.url}`);
128
+ return this.url;
129
+ }
130
+ const preferredPort = this.startPort;
131
+ const preferredUrl = `http://127.0.0.1:${preferredPort}`;
132
+ if (await this.isPortAvailable(preferredPort)) {
133
+ this.logger.info(`Port ${preferredPort} is available, starting new server...`);
134
+ await this.start();
135
+ return this.url;
136
+ }
137
+ this.logger.info(`Port ${preferredPort} is in use, checking if it's a translation server...`);
138
+ if (await this.checkIfTranslationServer(preferredUrl)) {
139
+ this.logger.info(`✅ Found existing translation server at ${preferredUrl}, reusing it`);
140
+ this.url = preferredUrl;
141
+ return preferredUrl;
142
+ }
143
+ this.logger.info(`Port ${preferredPort} is in use by another service, finding alternative...`);
144
+ await this.start();
145
+ return this.url;
146
+ }
147
+ /**
148
+ * Check if server is running
149
+ */
150
+ isRunning() {
151
+ return this.server !== null && this.url !== null;
152
+ }
153
+ /** No entry means no source text to send: the module was never transformed
154
+ * in this run, and it renders in the source language. */
155
+ warnAboutUnknownHashes(hashes) {
156
+ const unknown = hashes.filter((hash) => !this.metadata?.[hash]);
157
+ if (unknown.length === 0) return;
158
+ this.logger.warn(`${unknown.length} of ${hashes.length} hashes are not in the metadata store and cannot be translated: ${unknown.slice(0, 5).join(", ")}${unknown.length > 5 ? "…" : ""}`);
159
+ }
160
+ /**
161
+ * Reload metadata from disk
162
+ * Useful when metadata has been updated during runtime (e.g., new transformations)
163
+ */
164
+ async reloadMetadata() {
165
+ try {
166
+ this.metadata = await require_manager.loadMetadata(require_manager.getMetadataPath(this.config));
167
+ this.logger.debug(`Reloaded metadata: ${Object.keys(this.metadata).length} entries`);
168
+ } catch (error) {
169
+ this.logger.warn("Failed to reload metadata:", error);
170
+ this.metadata = {};
171
+ }
172
+ }
173
+ /**
174
+ * Translate the entire dictionary for a given locale
175
+ *
176
+ * This method always reloads metadata from disk before translating to ensure
177
+ * all entries added during build-time transformations are included.
178
+ *
179
+ * This is the recommended method for build-time translation generation.
180
+ */
181
+ async translateAll(locale) {
182
+ if (!this.translationService) throw new Error("Translation server not initialized");
183
+ await this.reloadMetadata();
184
+ if (!this.metadata) throw new Error("Failed to load metadata");
185
+ const allHashes = Object.keys(this.metadata);
186
+ this.logger.info(`Translating all ${allHashes.length} entries to ${locale}`);
187
+ const result = await this.translationService.translate(locale, this.metadata, allHashes);
188
+ if (result.unsupportedLocale) this.logger.warn(` [${locale}] ${result.errors[0]?.error}`);
189
+ else if (result.errors.length > 0) {
190
+ this.logger.error(`${result.errors.length} translation error(s) for ${locale}:`);
191
+ for (const err of result.errors) {
192
+ const prefix = ` [${locale}]`;
193
+ if (err.hash === "all") {
194
+ this.logger.error(`${prefix} ${err.error}`);
195
+ continue;
196
+ }
197
+ const source = err.sourceText.length > 200 ? err.sourceText.slice(0, 200) + "..." : err.sourceText;
198
+ this.logger.error(`${prefix} hash=${err.hash} source="${source}" error="${err.error}"`);
199
+ }
200
+ }
201
+ return result;
202
+ }
203
+ /**
204
+ * Find an available port starting from the given port
205
+ */
206
+ async findAvailablePort(startPort, maxAttempts = 100) {
207
+ for (let port = startPort; port < startPort + maxAttempts; port++) if (await this.isPortAvailable(port)) return port;
208
+ throw new Error(`Could not find available port in range ${startPort}-${startPort + maxAttempts}`);
209
+ }
210
+ /**
211
+ * Check if a port is available
212
+ */
213
+ async isPortAvailable(port) {
214
+ return new Promise((resolve) => {
215
+ const testServer = http.default.createServer();
216
+ testServer.once("error", (error) => {
217
+ if (error.code === "EADDRINUSE") resolve(false);
218
+ else resolve(false);
219
+ });
220
+ testServer.once("listening", () => {
221
+ testServer.close(() => {
222
+ resolve(true);
223
+ });
224
+ });
225
+ testServer.listen(port, "127.0.0.1");
226
+ });
227
+ }
228
+ /**
229
+ * Check if a given URL is running our translation server by calling the health endpoint
230
+ * Also verifies that the config hash matches to ensure compatible configuration
231
+ */
232
+ async checkIfTranslationServer(url$1) {
233
+ return new Promise((resolve) => {
234
+ const healthUrl = `${url$1}/health`;
235
+ const req = http.default.get(healthUrl, { timeout: 2e3 }, (res) => {
236
+ let data = "";
237
+ res.on("data", (chunk) => {
238
+ data += chunk.toString();
239
+ });
240
+ res.on("end", () => {
241
+ try {
242
+ if (res.statusCode === 200) {
243
+ const json = JSON.parse(data);
244
+ if (json.configHash && json.configHash !== this.configHash) {
245
+ this.logger.warn(`Existing server has different config (hash: ${json.configHash} vs ${this.configHash}), will start new server`);
246
+ resolve(false);
247
+ return;
248
+ }
249
+ resolve(true);
250
+ return;
251
+ }
252
+ resolve(false);
253
+ } catch (error) {
254
+ resolve(false);
255
+ }
256
+ });
257
+ });
258
+ req.on("error", () => {
259
+ resolve(false);
260
+ });
261
+ req.on("timeout", () => {
262
+ req.destroy();
263
+ resolve(false);
264
+ });
265
+ });
266
+ }
267
+ /**
268
+ * Handle incoming HTTP request
269
+ */
270
+ async handleRequest(req, res) {
271
+ this.logger.info(`🔄 Processing: ${req.method} ${req.url}`);
272
+ try {
273
+ const url$1 = new url.URL(req.url || "", `http://${req.headers.host}`);
274
+ this.logger.debug(`${req.method} ${url$1.pathname}`);
275
+ res.setHeader("Access-Control-Allow-Origin", "*");
276
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
277
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type");
278
+ res.setHeader("Access-Control-Expose-Headers", "Content-Type, Cache-Control");
279
+ if (req.method === "OPTIONS") {
280
+ res.writeHead(204);
281
+ res.end();
282
+ return;
283
+ }
284
+ if (url$1.pathname === "/health") {
285
+ res.writeHead(200, { "Content-Type": "application/json" });
286
+ res.end(JSON.stringify({
287
+ port: this.url,
288
+ configHash: this.configHash
289
+ }));
290
+ return;
291
+ }
292
+ const postMatch = url$1.pathname.match(/^\/translations\/([^/]+)$/);
293
+ if (postMatch && req.method === "POST") {
294
+ const [, locale] = postMatch;
295
+ await this.handleBatchTranslationRequest(locale, req, res);
296
+ return;
297
+ }
298
+ const dictMatch = url$1.pathname.match(/^\/translations\/([^/]+)$/);
299
+ if (dictMatch && req.method === "GET") {
300
+ const [, locale] = dictMatch;
301
+ await this.handleDictionaryRequest(locale, res);
302
+ return;
303
+ }
304
+ res.writeHead(404, { "Content-Type": "application/json" });
305
+ res.end(JSON.stringify({
306
+ error: "Not Found",
307
+ message: "Unknown endpoint",
308
+ availableEndpoints: [
309
+ "GET /health",
310
+ "GET /translations/:locale",
311
+ "POST /translations/:locale (with body: { hashes: string[] })"
312
+ ]
313
+ }));
314
+ } catch (error) {
315
+ this.logger.error("Error handling request:", error);
316
+ res.writeHead(500, { "Content-Type": "application/json" });
317
+ res.end(JSON.stringify({
318
+ error: "Internal Server Error",
319
+ message: error instanceof Error ? error.message : "Unknown error"
320
+ }));
321
+ }
322
+ }
323
+ /**
324
+ * Handle batch translation request
325
+ */
326
+ async handleBatchTranslationRequest(locale, req, res) {
327
+ try {
328
+ const parsedLocale = require_is_valid_locale.parseLocaleOrThrow(locale);
329
+ let body = "";
330
+ this.logger.debug("Reading request body...");
331
+ for await (const chunk of req) {
332
+ body += chunk.toString();
333
+ this.logger.debug(`Chunk read, body: ${body}`);
334
+ }
335
+ const { hashes } = JSON.parse(body);
336
+ this.logger.debug(`Parsed hashes: ${hashes.join(",")}`);
337
+ if (!Array.isArray(hashes)) {
338
+ res.writeHead(400, { "Content-Type": "application/json" });
339
+ res.end(JSON.stringify({
340
+ error: "Bad Request",
341
+ message: "Body must contain 'hashes' array"
342
+ }));
343
+ return;
344
+ }
345
+ await this.reloadMetadata();
346
+ if (!this.metadata) throw new Error("Failed to load metadata");
347
+ this.logger.info(`🔄 Translating ${hashes.length} hashes to ${locale}`);
348
+ this.logger.debug(`🔄 Hashes: ${hashes.join(", ")}`);
349
+ this.warnAboutUnknownHashes(hashes);
350
+ const result = await this.translationService.translate(parsedLocale, this.metadata, hashes);
351
+ res.writeHead(200, {
352
+ "Content-Type": "application/json",
353
+ "Cache-Control": "no-cache"
354
+ });
355
+ res.end(JSON.stringify({
356
+ locale,
357
+ translations: result.translations,
358
+ errors: result.errors
359
+ }));
360
+ } catch (error) {
361
+ this.logger.error(`Error getting batch translations for ${locale}:`, error);
362
+ res.writeHead(500, { "Content-Type": "application/json" });
363
+ res.end(JSON.stringify({
364
+ error: "Translation generation failed",
365
+ message: error instanceof Error ? error.message : "Unknown error"
366
+ }));
367
+ }
368
+ }
369
+ /**
370
+ * Handle request for full translation dictionary
371
+ */
372
+ async handleDictionaryRequest(locale, res) {
373
+ try {
374
+ const parsedLocale = require_is_valid_locale.parseLocaleOrThrow(locale);
375
+ await this.reloadMetadata();
376
+ if (!this.metadata) throw new Error("Failed to load metadata");
377
+ this.logger.info(`🌐 Requesting full dictionary for ${locale}`);
378
+ const allHashes = Object.keys(this.metadata);
379
+ const result = await this.translationService.translate(parsedLocale, this.metadata, allHashes);
380
+ res.writeHead(200, {
381
+ "Content-Type": "application/json",
382
+ "Cache-Control": "public, max-age=3600"
383
+ });
384
+ res.end(JSON.stringify({
385
+ locale,
386
+ translations: result.translations,
387
+ errors: result.errors
388
+ }));
389
+ } catch (error) {
390
+ this.logger.error(`Error getting dictionary for ${locale}:`, error);
391
+ res.writeHead(500, { "Content-Type": "application/json" });
392
+ res.end(JSON.stringify({
393
+ error: "Translation generation failed",
394
+ message: error instanceof Error ? error.message : "Unknown error"
395
+ }));
396
+ }
397
+ }
398
+ };
399
+ function stableStringify(value) {
400
+ const normalize = (v) => {
401
+ if (v === void 0) return void 0;
402
+ if (typeof v === "function") return void 0;
403
+ if (v === null) return null;
404
+ if (Array.isArray(v)) return v.map(normalize).filter((x) => x !== void 0);
405
+ if (typeof v === "object") {
406
+ const out = {};
407
+ for (const key of Object.keys(v).sort()) {
408
+ const next = normalize(v[key]);
409
+ if (next !== void 0) out[key] = next;
410
+ }
411
+ return out;
412
+ }
413
+ return v;
414
+ };
415
+ return JSON.stringify(normalize(value));
416
+ }
417
+ /**
418
+ * Generate a stable hash of a config object
419
+ * Filters out functions and non-serializable values
420
+ * Sorts keys for stability
421
+ */
422
+ function hashConfig(config) {
423
+ const serialized = stableStringify(config);
424
+ return crypto.default.createHash("md5").update(serialized).digest("hex").slice(0, 12);
425
+ }
426
+ async function startTranslationServer(options) {
427
+ const server = new TranslationServer(options);
428
+ await server.start();
429
+ return server;
430
+ }
431
+ /**
432
+ * Create a translation server and start it or reuse an existing one on the preferred port
433
+ *
434
+ * Since we have little control over the dev server start in next, we can start the translation server only in the async config or in the loader,
435
+ * they both could be run in different processes, and we need a way to avoid starting multiple servers.
436
+ * This one will try to start a server on the preferred port (which seems to be an atomic operation), and if it fails,
437
+ * it checks if the server that is already started is ours and returns its url.
438
+ *
439
+ * @returns Object containing the server instance and its URL
440
+ */
441
+ async function startOrGetTranslationServer(options) {
442
+ const server = new TranslationServer(options);
443
+ return {
444
+ server,
445
+ url: await server.startOrGetUrl()
446
+ };
447
+ }
448
+
449
+ //#endregion
450
+ exports.startOrGetTranslationServer = startOrGetTranslationServer;
451
+ exports.startTranslationServer = startTranslationServer;