@weglot/translate-react 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +6 -0
  3. package/README.md +190 -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 +207 -0
  18. package/build/plugin/build-translator.mjs +205 -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 +226 -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 +228 -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 +142 -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 +139 -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 +137 -0
  229. package/build/translators/translation-service.mjs +138 -0
  230. package/build/translators/translation-service.mjs.map +1 -0
  231. package/build/translators/weglot/api-client.cjs +79 -0
  232. package/build/translators/weglot/api-client.mjs +79 -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 +46 -0
  238. package/build/translators/weglot/engine.mjs +43 -0
  239. package/build/translators/weglot/engine.mjs.map +1 -0
  240. package/build/translators/weglot/translator.cjs +61 -0
  241. package/build/translators/weglot/translator.mjs +62 -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 +143 -0
  247. package/build/types.d.cts.map +1 -0
  248. package/build/types.d.mts +143 -0
  249. package/build/types.d.mts.map +1 -0
  250. package/build/utils/config-factory.cjs +86 -0
  251. package/build/utils/config-factory.mjs +83 -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 +56 -0
  269. package/build/virtual/code-generator.mjs +55 -0
  270. package/build/virtual/code-generator.mjs.map +1 -0
  271. package/build/virtual/config.cjs +16 -0
  272. package/build/virtual/config.d.cts +13 -0
  273. package/build/virtual/config.d.cts.map +1 -0
  274. package/build/virtual/config.d.mts +13 -0
  275. package/build/virtual/config.d.mts.map +1 -0
  276. package/build/virtual/config.mjs +12 -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,129 @@
1
+ import { DEFAULT_MODERN_ENGINE, fallbackWireTagFor, mergeableTagsFor } from "./engine.mjs";
2
+
3
+ //#region src/translators/weglot/wire-format.ts
4
+ /**
5
+ * Converts the stored ICU form to the wire form the API accepts and back:
6
+ * `Read <strong0>this</strong0>` ↔ `Read <strong wg-1="">this</strong>`.
7
+ */
8
+ const STORED_TOKEN = /\{[^{}]+\}|<([A-Za-z][A-Za-z0-9]*)\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
9
+ const WIRE_TOKEN = /<([A-Za-z][A-Za-z0-9]*)\s+wg-(\d+)(?:="")?\s*>|<\/([A-Za-z][A-Za-z0-9]*)\s*>/g;
10
+ const TAG_SHAPED = /<\/?([A-Za-z][A-Za-z0-9]*)(\s[^<>]*?)?\s*\/?>/g;
11
+ const ICU_QUOTE_BEFORE_SYNTAX = /(?<!')'(?=[{}<])/g;
12
+ const VOID_TAGS = new Set([
13
+ "area",
14
+ "base",
15
+ "br",
16
+ "col",
17
+ "embed",
18
+ "hr",
19
+ "img",
20
+ "input",
21
+ "link",
22
+ "meta",
23
+ "source",
24
+ "track",
25
+ "wbr"
26
+ ]);
27
+ function wireTagFor(icuName, tags, fallbackTag) {
28
+ const base = icuName.replace(/\d+$/, "");
29
+ if (VOID_TAGS.has(base)) return fallbackTag;
30
+ return tags.has(base) ? base : fallbackTag;
31
+ }
32
+ function encodeForApi(text, engine = DEFAULT_MODERN_ENGINE) {
33
+ const tags = mergeableTagsFor(engine);
34
+ const fallbackTag = fallbackWireTagFor(tags);
35
+ const slots = [];
36
+ const openSlots = [];
37
+ let wire = "";
38
+ let cursor = 0;
39
+ if (fallbackTag === void 0) {
40
+ const carriesMarkup = STORED_TOKEN.test(text);
41
+ STORED_TOKEN.lastIndex = 0;
42
+ return {
43
+ wire: text,
44
+ restore: (translated) => ({
45
+ text: translated,
46
+ damaged: false
47
+ }),
48
+ encodable: !carriesMarkup
49
+ };
50
+ }
51
+ for (const match of text.matchAll(STORED_TOKEN)) {
52
+ wire += text.slice(cursor, match.index);
53
+ cursor = match.index + match[0].length;
54
+ const [token, openName, closeName] = match;
55
+ if (openName !== void 0) {
56
+ const slot = {
57
+ kind: "tag",
58
+ icuName: openName,
59
+ wireName: wireTagFor(openName, tags, fallbackTag)
60
+ };
61
+ openSlots.push(slots.push(slot) - 1);
62
+ wire += `<${slot.wireName} wg-${slots.length}="">`;
63
+ } else if (closeName !== void 0) {
64
+ const index = openSlots.pop();
65
+ const slot = index === void 0 ? void 0 : slots[index];
66
+ if (slot?.kind === "tag") wire += `</${slot.wireName}>`;
67
+ } else {
68
+ slots.push({
69
+ kind: "placeholder",
70
+ value: token
71
+ });
72
+ wire += `<${fallbackTag} wg-${slots.length}=""></${fallbackTag}>`;
73
+ }
74
+ }
75
+ wire += text.slice(cursor);
76
+ return {
77
+ wire,
78
+ restore: (translated) => restore(translated, slots),
79
+ encodable: true
80
+ };
81
+ }
82
+ function restore(translated, slots) {
83
+ const stack = [];
84
+ const seen = /* @__PURE__ */ new Set();
85
+ let text = "";
86
+ let cursor = 0;
87
+ let suppressed = 0;
88
+ for (const match of translated.matchAll(WIRE_TOKEN)) {
89
+ if (!suppressed) text += translated.slice(cursor, match.index);
90
+ cursor = match.index + match[0].length;
91
+ const [, , markerIndex, closeName] = match;
92
+ if (markerIndex !== void 0) {
93
+ const index = Number(markerIndex) - 1;
94
+ const slot = slots[index];
95
+ if (!slot) {
96
+ stack.push(void 0);
97
+ continue;
98
+ }
99
+ seen.add(index);
100
+ stack.push(slot);
101
+ if (slot.kind === "placeholder") {
102
+ if (!suppressed) text += slot.value;
103
+ suppressed++;
104
+ } else if (!suppressed) text += `<${slot.icuName}>`;
105
+ } else if (closeName !== void 0) {
106
+ const slot = stack.pop();
107
+ if (!slot) continue;
108
+ if (slot.kind === "placeholder") suppressed--;
109
+ else if (!suppressed) text += `</${slot.icuName}>`;
110
+ }
111
+ }
112
+ if (!suppressed) text += translated.slice(cursor);
113
+ text = text.replace(ICU_QUOTE_BEFORE_SYNTAX, "''");
114
+ const lostSlot = slots.some((_, index) => !seen.has(index));
115
+ return {
116
+ text,
117
+ damaged: lostSlot || hasStrayMarkup(text, slots)
118
+ };
119
+ }
120
+ /** Invented markup or a leftover marker would reach intl-messageformat as an
121
+ * unknown tag and throw at render time. */
122
+ function hasStrayMarkup(text, slots) {
123
+ const known = new Set(slots.flatMap((slot) => slot.kind === "tag" ? [slot.icuName] : []));
124
+ return [...text.matchAll(TAG_SHAPED)].some(([, name, attributes]) => !known.has(name) || attributes !== void 0);
125
+ }
126
+
127
+ //#endregion
128
+ export { encodeForApi };
129
+ //# sourceMappingURL=wire-format.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire-format.mjs","names":["VOID_TAGS: ReadonlySet<string>","slots: Slot[]","openSlots: number[]","slot: Slot","stack: (Slot | undefined)[]"],"sources":["../../../src/translators/weglot/wire-format.ts"],"sourcesContent":["/**\n * Converts the stored ICU form to the wire form the API accepts and back:\n * `Read <strong0>this</strong0>` ↔ `Read <strong wg-1=\"\">this</strong>`.\n */\n\nimport {\n DEFAULT_MODERN_ENGINE,\n fallbackWireTagFor,\n mergeableTagsFor,\n} from \"./engine\";\n\n// A placeholder, an opening ICU tag, or a closing ICU tag in the stored form.\nconst STORED_TOKEN =\n /\\{[^{}]+\\}|<([A-Za-z][A-Za-z0-9]*)\\s*>|<\\/([A-Za-z][A-Za-z0-9]*)\\s*>/g;\n\n// An opening tag carrying a marker, or any closing tag, in the API response.\n// The `=\"\"` is optional: machine translation sometimes drops the empty value.\nconst WIRE_TOKEN =\n /<([A-Za-z][A-Za-z0-9]*)\\s+wg-(\\d+)(?:=\"\")?\\s*>|<\\/([A-Za-z][A-Za-z0-9]*)\\s*>/g;\n\n// Anything shaped like a tag, with its attributes if it carries any: a\n// leftover marker or an element the engine invented.\nconst TAG_SHAPED = /<\\/?([A-Za-z][A-Za-z0-9]*)(\\s[^<>]*?)?\\s*\\/?>/g;\n\n// A lone apostrophe before markup opens an ICU quoted literal, turning the\n// markup into text (\"l'<strong>\"). Doubling keeps it text; a pair is escaped.\nconst ICU_QUOTE_BEFORE_SYNTAX = /(?<!')'(?=[{}<])/g;\n\ntype Slot =\n | { kind: \"placeholder\"; value: string }\n | { kind: \"tag\"; icuName: string; wireName: string };\n\nexport interface RestoredTranslation {\n text: string;\n /** True when a marker went missing or the result still holds stray markup. */\n damaged: boolean;\n}\n\n// The wire form always sends a pair, and `<br wg-1=\"\"></br>` comes back with a\n// stray closing tag. These travel under the fallback name; restore maps by index.\nconst VOID_TAGS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\nfunction wireTagFor(\n icuName: string,\n tags: ReadonlySet<string>,\n fallbackTag: string,\n): string {\n const base = icuName.replace(/\\d+$/, \"\");\n if (VOID_TAGS.has(base)) return fallbackTag;\n return tags.has(base) ? base : fallbackTag;\n}\n\nexport interface EncodedForApi {\n wire: string;\n restore: (translated: string) => RestoredTranslation;\n /** False when the engine permits no tag for the markup (engine 1 only), so the\n * caller keeps the source text. */\n encodable: boolean;\n}\n\nexport function encodeForApi(\n text: string,\n engine: number = DEFAULT_MODERN_ENGINE,\n): EncodedForApi {\n const tags = mergeableTagsFor(engine);\n const fallbackTag = fallbackWireTagFor(tags);\n const slots: Slot[] = [];\n const openSlots: number[] = [];\n let wire = \"\";\n let cursor = 0;\n\n if (fallbackTag === undefined) {\n const carriesMarkup = STORED_TOKEN.test(text);\n STORED_TOKEN.lastIndex = 0;\n return {\n wire: text,\n restore: (translated) => ({ text: translated, damaged: false }),\n encodable: !carriesMarkup,\n };\n }\n\n for (const match of text.matchAll(STORED_TOKEN)) {\n wire += text.slice(cursor, match.index);\n cursor = match.index + match[0].length;\n\n const [token, openName, closeName] = match;\n\n if (openName !== undefined) {\n const slot: Slot = {\n kind: \"tag\",\n icuName: openName,\n wireName: wireTagFor(openName, tags, fallbackTag),\n };\n openSlots.push(slots.push(slot) - 1);\n wire += `<${slot.wireName} wg-${slots.length}=\"\">`;\n } else if (closeName !== undefined) {\n const index = openSlots.pop();\n const slot = index === undefined ? undefined : slots[index];\n // A closing tag with no opening cannot be mapped back; drop it.\n if (slot?.kind === \"tag\") {\n wire += `</${slot.wireName}>`;\n }\n } else {\n slots.push({ kind: \"placeholder\", value: token });\n wire += `<${fallbackTag} wg-${slots.length}=\"\"></${fallbackTag}>`;\n }\n }\n\n wire += text.slice(cursor);\n\n return {\n wire,\n restore: (translated) => restore(translated, slots),\n encodable: true,\n };\n}\n\nfunction restore(translated: string, slots: Slot[]): RestoredTranslation {\n const stack: (Slot | undefined)[] = [];\n const seen = new Set<number>();\n let text = \"\";\n let cursor = 0;\n // Content translation put inside an empty placeholder tag is dropped.\n let suppressed = 0;\n\n for (const match of translated.matchAll(WIRE_TOKEN)) {\n if (!suppressed) {\n text += translated.slice(cursor, match.index);\n }\n cursor = match.index + match[0].length;\n\n const [, , markerIndex, closeName] = match;\n\n if (markerIndex !== undefined) {\n const index = Number(markerIndex) - 1;\n const slot = slots[index];\n if (!slot) {\n // Marker we never sent: keep the content, drop the tag.\n stack.push(undefined);\n continue;\n }\n seen.add(index);\n stack.push(slot);\n if (slot.kind === \"placeholder\") {\n if (!suppressed) text += slot.value;\n suppressed++;\n } else if (!suppressed) {\n text += `<${slot.icuName}>`;\n }\n } else if (closeName !== undefined) {\n const slot = stack.pop();\n if (!slot) continue;\n if (slot.kind === \"placeholder\") {\n suppressed--;\n } else if (!suppressed) {\n text += `</${slot.icuName}>`;\n }\n }\n }\n\n if (!suppressed) {\n text += translated.slice(cursor);\n }\n\n text = text.replace(ICU_QUOTE_BEFORE_SYNTAX, \"''\");\n\n const lostSlot = slots.some((_, index) => !seen.has(index));\n return { text, damaged: lostSlot || hasStrayMarkup(text, slots) };\n}\n\n/** Invented markup or a leftover marker would reach intl-messageformat as an\n * unknown tag and throw at render time. */\nfunction hasStrayMarkup(text: string, slots: Slot[]): boolean {\n const known = new Set(\n slots.flatMap((slot) => (slot.kind === \"tag\" ? [slot.icuName] : [])),\n );\n // Only tag-shaped leftovers matter; a bare \"<\" is legitimate text.\n return [...text.matchAll(TAG_SHAPED)].some(\n ([, name, attributes]) => !known.has(name) || attributes !== undefined,\n );\n}\n"],"mappings":";;;;;;;AAYA,MAAM,eACJ;AAIF,MAAM,aACJ;AAIF,MAAM,aAAa;AAInB,MAAM,0BAA0B;AAchC,MAAMA,YAAiC,IAAI,IAAI;CAC7C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAS,WACP,SACA,MACA,aACQ;CACR,MAAM,OAAO,QAAQ,QAAQ,QAAQ,GAAG;AACxC,KAAI,UAAU,IAAI,KAAK,CAAE,QAAO;AAChC,QAAO,KAAK,IAAI,KAAK,GAAG,OAAO;;AAWjC,SAAgB,aACd,MACA,SAAiB,uBACF;CACf,MAAM,OAAO,iBAAiB,OAAO;CACrC,MAAM,cAAc,mBAAmB,KAAK;CAC5C,MAAMC,QAAgB,EAAE;CACxB,MAAMC,YAAsB,EAAE;CAC9B,IAAI,OAAO;CACX,IAAI,SAAS;AAEb,KAAI,gBAAgB,QAAW;EAC7B,MAAM,gBAAgB,aAAa,KAAK,KAAK;AAC7C,eAAa,YAAY;AACzB,SAAO;GACL,MAAM;GACN,UAAU,gBAAgB;IAAE,MAAM;IAAY,SAAS;IAAO;GAC9D,WAAW,CAAC;GACb;;AAGH,MAAK,MAAM,SAAS,KAAK,SAAS,aAAa,EAAE;AAC/C,UAAQ,KAAK,MAAM,QAAQ,MAAM,MAAM;AACvC,WAAS,MAAM,QAAQ,MAAM,GAAG;EAEhC,MAAM,CAAC,OAAO,UAAU,aAAa;AAErC,MAAI,aAAa,QAAW;GAC1B,MAAMC,OAAa;IACjB,MAAM;IACN,SAAS;IACT,UAAU,WAAW,UAAU,MAAM,YAAY;IAClD;AACD,aAAU,KAAK,MAAM,KAAK,KAAK,GAAG,EAAE;AACpC,WAAQ,IAAI,KAAK,SAAS,MAAM,MAAM,OAAO;aACpC,cAAc,QAAW;GAClC,MAAM,QAAQ,UAAU,KAAK;GAC7B,MAAM,OAAO,UAAU,SAAY,SAAY,MAAM;AAErD,OAAI,MAAM,SAAS,MACjB,SAAQ,KAAK,KAAK,SAAS;SAExB;AACL,SAAM,KAAK;IAAE,MAAM;IAAe,OAAO;IAAO,CAAC;AACjD,WAAQ,IAAI,YAAY,MAAM,MAAM,OAAO,QAAQ,YAAY;;;AAInE,SAAQ,KAAK,MAAM,OAAO;AAE1B,QAAO;EACL;EACA,UAAU,eAAe,QAAQ,YAAY,MAAM;EACnD,WAAW;EACZ;;AAGH,SAAS,QAAQ,YAAoB,OAAoC;CACvE,MAAMC,QAA8B,EAAE;CACtC,MAAM,uBAAO,IAAI,KAAa;CAC9B,IAAI,OAAO;CACX,IAAI,SAAS;CAEb,IAAI,aAAa;AAEjB,MAAK,MAAM,SAAS,WAAW,SAAS,WAAW,EAAE;AACnD,MAAI,CAAC,WACH,SAAQ,WAAW,MAAM,QAAQ,MAAM,MAAM;AAE/C,WAAS,MAAM,QAAQ,MAAM,GAAG;EAEhC,MAAM,KAAK,aAAa,aAAa;AAErC,MAAI,gBAAgB,QAAW;GAC7B,MAAM,QAAQ,OAAO,YAAY,GAAG;GACpC,MAAM,OAAO,MAAM;AACnB,OAAI,CAAC,MAAM;AAET,UAAM,KAAK,OAAU;AACrB;;AAEF,QAAK,IAAI,MAAM;AACf,SAAM,KAAK,KAAK;AAChB,OAAI,KAAK,SAAS,eAAe;AAC/B,QAAI,CAAC,WAAY,SAAQ,KAAK;AAC9B;cACS,CAAC,WACV,SAAQ,IAAI,KAAK,QAAQ;aAElB,cAAc,QAAW;GAClC,MAAM,OAAO,MAAM,KAAK;AACxB,OAAI,CAAC,KAAM;AACX,OAAI,KAAK,SAAS,cAChB;YACS,CAAC,WACV,SAAQ,KAAK,KAAK,QAAQ;;;AAKhC,KAAI,CAAC,WACH,SAAQ,WAAW,MAAM,OAAO;AAGlC,QAAO,KAAK,QAAQ,yBAAyB,KAAK;CAElD,MAAM,WAAW,MAAM,MAAM,GAAG,UAAU,CAAC,KAAK,IAAI,MAAM,CAAC;AAC3D,QAAO;EAAE;EAAM,SAAS,YAAY,eAAe,MAAM,MAAM;EAAE;;;;AAKnE,SAAS,eAAe,MAAc,OAAwB;CAC5D,MAAM,QAAQ,IAAI,IAChB,MAAM,SAAS,SAAU,KAAK,SAAS,QAAQ,CAAC,KAAK,QAAQ,GAAG,EAAE,CAAE,CACrE;AAED,QAAO,CAAC,GAAG,KAAK,SAAS,WAAW,CAAC,CAAC,MACnC,GAAG,MAAM,gBAAgB,CAAC,MAAM,IAAI,KAAK,IAAI,eAAe,OAC9D"}
@@ -0,0 +1,143 @@
1
+ import { LocaleCode } from "./locale.cjs";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Cookie configuration for locale persistence
7
+ */
8
+ interface CookieConfig {
9
+ /**
10
+ * Name of the cookie to store the locale
11
+ * @default 'locale'
12
+ */
13
+ name: string;
14
+ /**
15
+ * Maximum age of the cookie in seconds
16
+ * @default 31536000 (1 year)
17
+ */
18
+ maxAge: number;
19
+ }
20
+ /**
21
+ * Locale persistence configuration
22
+ * Currently only supports cookie-based persistence
23
+ */
24
+ type LocalePersistenceConfig = {
25
+ type: "cookie";
26
+ config: CookieConfig;
27
+ };
28
+ /**
29
+ * Fields that are resolved internally (from the Weglot project settings or the
30
+ * environment) rather than provided by users.
31
+ */
32
+ type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "weglotDir";
33
+ /**
34
+ * Configuration for @weglot/translate-react
35
+ */
36
+ type PartialWeglotConfig = Partial<Omit<WeglotConfig, WeglotInternalFields | "dev"> & {
37
+ dev: Partial<WeglotConfig["dev"]>;
38
+ }>;
39
+ type WeglotEnvironment = "development" | "production";
40
+ /**
41
+ * Weglot config with all the defaults applied
42
+ */
43
+ type WeglotConfig = {
44
+ /** Weglot project API key. Falls back to the WEGLOT_API_KEY env var. */
45
+ apiKey: string;
46
+ /**
47
+ * Root directory of the source code
48
+ */
49
+ sourceRoot: string;
50
+ /**
51
+ * Directory for weglot files, relative to sourceRoot (e.g. `src/weglot/`).
52
+ *
53
+ * Fixed; not publicly configurable.
54
+ *
55
+ * @default "weglot"
56
+ * @internal
57
+ */
58
+ weglotDir: string;
59
+ /**
60
+ * Environment mode
61
+ * Determines metadata file naming and translator behavior
62
+ *
63
+ * @default "production"
64
+ * @internal
65
+ */
66
+ environment: WeglotEnvironment;
67
+ /**
68
+ * Cache implementation type
69
+ * - "local": Local file system cache (default)
70
+ * - "remote": Remote cache (future)
71
+ *
72
+ * @default "local"
73
+ * @internal Since we do not support more types, there is no need to make it public, but it allows keeping the config in the single place
74
+ */
75
+ cacheType: "local";
76
+ /**
77
+ * The locale to translate from.
78
+ *
79
+ * Resolved from the Weglot project settings.
80
+ *
81
+ * @internal
82
+ */
83
+ sourceLocale: LocaleCode;
84
+ /**
85
+ * The locale(s) to translate to.
86
+ *
87
+ * Resolved from the Weglot project settings.
88
+ *
89
+ * @internal
90
+ */
91
+ targetLocales: LocaleCode[];
92
+ /** Public locale to the code the translate API expects, for languages with a
93
+ * custom code. Resolved from the project settings. @internal */
94
+ apiLocales: Record<string, LocaleCode>;
95
+ /** Inline elements allowed inside a segment, from the project settings or the
96
+ * key length. @internal */
97
+ translationEngine: number;
98
+ /**
99
+ * Whether to require 'use i18n' directive
100
+ */
101
+ useDirective: boolean;
102
+ /**
103
+ * Which JSX attributes hold translatable text, per element, as deltas on the
104
+ * built-in list — `{ "*": ["!label"], PageTitle: ["subTitle"] }`. See the README.
105
+ */
106
+ translatableAttributes: Record<string, string[]>;
107
+ /**
108
+ * Development-specific settings
109
+ */
110
+ dev: {
111
+ /**
112
+ * Starting port for the translation server in development mode
113
+ * Server will try this port first, then increment if unavailable
114
+ *
115
+ * @default 60000
116
+ */
117
+ translationServerStartPort: number;
118
+ /**
119
+ * URL of the translation server in development mode if you manually start it
120
+ */
121
+ translationServerUrl?: string;
122
+ };
123
+ /**
124
+ * Locale persistence configuration
125
+ * Defines how locale changes should be persisted
126
+ *
127
+ * @default { type: 'cookie', config: { name: 'locale' } }
128
+ */
129
+ localePersistence: LocalePersistenceConfig;
130
+ /**
131
+ * Build mode for CI/production
132
+ * - "translate": Generate translations at build time, fail if translation fails (default)
133
+ * - "cache-only": Only use cached translations, fail if cache is incomplete
134
+ *
135
+ * Can be overridden by WEGLOT_BUILD_MODE environment variable
136
+ *
137
+ * @default "translate"
138
+ */
139
+ buildMode: "translate" | "cache-only";
140
+ };
141
+ //#endregion
142
+ export { CookieConfig, PartialWeglotConfig };
143
+ //# sourceMappingURL=types.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAYA;AACO,UArCU,YAAA,CAqCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EA6CgB,MAAA,EAAA,MAAA;;;;;;AAsD4B,KAhIhC,uBAAA,GAgIgC;;UAhIoB;;;;;;KAMpD,oBAAA;;;;KAYA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;eA0BG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;0BAeH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
@@ -0,0 +1,143 @@
1
+ import { LocaleCode } from "./locale.mjs";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * Cookie configuration for locale persistence
7
+ */
8
+ interface CookieConfig {
9
+ /**
10
+ * Name of the cookie to store the locale
11
+ * @default 'locale'
12
+ */
13
+ name: string;
14
+ /**
15
+ * Maximum age of the cookie in seconds
16
+ * @default 31536000 (1 year)
17
+ */
18
+ maxAge: number;
19
+ }
20
+ /**
21
+ * Locale persistence configuration
22
+ * Currently only supports cookie-based persistence
23
+ */
24
+ type LocalePersistenceConfig = {
25
+ type: "cookie";
26
+ config: CookieConfig;
27
+ };
28
+ /**
29
+ * Fields that are resolved internally (from the Weglot project settings or the
30
+ * environment) rather than provided by users.
31
+ */
32
+ type WeglotInternalFields = "environment" | "cacheType" | "sourceLocale" | "targetLocales" | "apiLocales" | "translationEngine" | "weglotDir";
33
+ /**
34
+ * Configuration for @weglot/translate-react
35
+ */
36
+ type PartialWeglotConfig = Partial<Omit<WeglotConfig, WeglotInternalFields | "dev"> & {
37
+ dev: Partial<WeglotConfig["dev"]>;
38
+ }>;
39
+ type WeglotEnvironment = "development" | "production";
40
+ /**
41
+ * Weglot config with all the defaults applied
42
+ */
43
+ type WeglotConfig = {
44
+ /** Weglot project API key. Falls back to the WEGLOT_API_KEY env var. */
45
+ apiKey: string;
46
+ /**
47
+ * Root directory of the source code
48
+ */
49
+ sourceRoot: string;
50
+ /**
51
+ * Directory for weglot files, relative to sourceRoot (e.g. `src/weglot/`).
52
+ *
53
+ * Fixed; not publicly configurable.
54
+ *
55
+ * @default "weglot"
56
+ * @internal
57
+ */
58
+ weglotDir: string;
59
+ /**
60
+ * Environment mode
61
+ * Determines metadata file naming and translator behavior
62
+ *
63
+ * @default "production"
64
+ * @internal
65
+ */
66
+ environment: WeglotEnvironment;
67
+ /**
68
+ * Cache implementation type
69
+ * - "local": Local file system cache (default)
70
+ * - "remote": Remote cache (future)
71
+ *
72
+ * @default "local"
73
+ * @internal Since we do not support more types, there is no need to make it public, but it allows keeping the config in the single place
74
+ */
75
+ cacheType: "local";
76
+ /**
77
+ * The locale to translate from.
78
+ *
79
+ * Resolved from the Weglot project settings.
80
+ *
81
+ * @internal
82
+ */
83
+ sourceLocale: LocaleCode;
84
+ /**
85
+ * The locale(s) to translate to.
86
+ *
87
+ * Resolved from the Weglot project settings.
88
+ *
89
+ * @internal
90
+ */
91
+ targetLocales: LocaleCode[];
92
+ /** Public locale to the code the translate API expects, for languages with a
93
+ * custom code. Resolved from the project settings. @internal */
94
+ apiLocales: Record<string, LocaleCode>;
95
+ /** Inline elements allowed inside a segment, from the project settings or the
96
+ * key length. @internal */
97
+ translationEngine: number;
98
+ /**
99
+ * Whether to require 'use i18n' directive
100
+ */
101
+ useDirective: boolean;
102
+ /**
103
+ * Which JSX attributes hold translatable text, per element, as deltas on the
104
+ * built-in list — `{ "*": ["!label"], PageTitle: ["subTitle"] }`. See the README.
105
+ */
106
+ translatableAttributes: Record<string, string[]>;
107
+ /**
108
+ * Development-specific settings
109
+ */
110
+ dev: {
111
+ /**
112
+ * Starting port for the translation server in development mode
113
+ * Server will try this port first, then increment if unavailable
114
+ *
115
+ * @default 60000
116
+ */
117
+ translationServerStartPort: number;
118
+ /**
119
+ * URL of the translation server in development mode if you manually start it
120
+ */
121
+ translationServerUrl?: string;
122
+ };
123
+ /**
124
+ * Locale persistence configuration
125
+ * Defines how locale changes should be persisted
126
+ *
127
+ * @default { type: 'cookie', config: { name: 'locale' } }
128
+ */
129
+ localePersistence: LocalePersistenceConfig;
130
+ /**
131
+ * Build mode for CI/production
132
+ * - "translate": Generate translations at build time, fail if translation fails (default)
133
+ * - "cache-only": Only use cached translations, fail if cache is incomplete
134
+ *
135
+ * Can be overridden by WEGLOT_BUILD_MODE environment variable
136
+ *
137
+ * @default "translate"
138
+ */
139
+ buildMode: "translate" | "cache-only";
140
+ };
141
+ //#endregion
142
+ export { CookieConfig, PartialWeglotConfig };
143
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;AA2BA;AAMA;AAYA;AACO,UArCU,YAAA,CAqCV;EAAc;;;;EADa,IAAA,EAAA,MAAA;EAAO;AAMzC;AAKA;;EA6CgB,MAAA,EAAA,MAAA;;;;;;AAsD4B,KAhIhC,uBAAA,GAgIgC;;UAhIoB;;;;;;KAMpD,oBAAA;;;;KAYA,mBAAA,GAAsB,QAChC,KAAK,cAAc;OACZ,QAAQ;;KAIL,iBAAA;;;;KAKA,YAAA;;;;;;;;;;;;;;;;;;;;;;;eA0BG;;;;;;;;;;;;;;;;;gBAmBC;;;;;;;;iBASC;;;cAIH,eAAe;;;;;;;;;;;;0BAeH;;;;;;;;;;;;;;;;;;;;;;;qBA0BL"}
@@ -0,0 +1,86 @@
1
+ const require_api_client = require('../translators/weglot/api-client.cjs');
2
+ const require_engine = require('../translators/weglot/engine.cjs');
3
+ require("dotenv/config");
4
+
5
+ //#region src/utils/config-factory.ts
6
+ /**
7
+ * Config factory for creating LoaderConfig instances
8
+ */
9
+ /**
10
+ * Default configuration values
11
+ */
12
+ const DEFAULT_CONFIG = {
13
+ sourceRoot: "src",
14
+ weglotDir: "weglot",
15
+ useDirective: false,
16
+ translatableAttributes: {},
17
+ dev: { translationServerStartPort: 6e4 },
18
+ localePersistence: {
19
+ type: "cookie",
20
+ config: {
21
+ name: "locale",
22
+ maxAge: 31536e3
23
+ }
24
+ },
25
+ buildMode: "translate"
26
+ };
27
+ /**
28
+ * Create a LoaderConfig with defaults applied
29
+ *
30
+ * @param options - Partial config to override defaults
31
+ * @returns Complete LoaderConfig with all defaults applied
32
+ *
33
+ */
34
+ function createWeglotConfig(options) {
35
+ const cleanOptions = { ...options };
36
+ const cleanObject = (obj) => {
37
+ if (!obj || typeof obj !== "object") return;
38
+ Object.keys(obj).forEach((key) => {
39
+ if (obj[key] === void 0) delete obj[key];
40
+ else if (obj[key] && typeof obj[key] === "object" && !Array.isArray(obj[key])) cleanObject(obj[key]);
41
+ });
42
+ };
43
+ cleanObject(cleanOptions);
44
+ const apiKey = cleanOptions.apiKey ?? process.env.WEGLOT_API_KEY;
45
+ if (!apiKey) throw new Error("Weglot project key is missing. Pass `apiKey` in the plugin options or set the WEGLOT_API_KEY environment variable.");
46
+ return {
47
+ ...DEFAULT_CONFIG,
48
+ ...cleanOptions,
49
+ apiKey,
50
+ sourceLocale: cleanOptions.sourceLocale ?? "",
51
+ targetLocales: cleanOptions.targetLocales ?? [],
52
+ apiLocales: cleanOptions.apiLocales ?? {},
53
+ translationEngine: cleanOptions.translationEngine ?? require_engine.resolveTranslationEngine(apiKey),
54
+ environment: cleanOptions.environment ?? (process.env.NODE_ENV === "development" ? "development" : "production"),
55
+ cacheType: cleanOptions.cacheType ?? "local",
56
+ dev: {
57
+ ...DEFAULT_CONFIG.dev,
58
+ ...cleanOptions.dev
59
+ },
60
+ localePersistence: {
61
+ ...DEFAULT_CONFIG.localePersistence,
62
+ ...cleanOptions.localePersistence,
63
+ config: {
64
+ ...DEFAULT_CONFIG.localePersistence.config,
65
+ ...cleanOptions.localePersistence?.config
66
+ }
67
+ }
68
+ };
69
+ }
70
+ /**
71
+ * Fetches source/target locales from the Weglot project settings.
72
+ * Idempotent: no-ops when locales are already resolved (e.g. passed
73
+ * through Next.js loader options).
74
+ */
75
+ async function resolveProjectLanguages(config, client = new require_api_client.WeglotApiClient(config.apiKey)) {
76
+ if (config.sourceLocale && config.targetLocales.length > 0) return;
77
+ const settings = await client.fetchSettings();
78
+ config.sourceLocale = settings.sourceLocale;
79
+ config.targetLocales = settings.targetLocales;
80
+ config.apiLocales = settings.apiLocales;
81
+ config.translationEngine = require_engine.resolveTranslationEngine(config.apiKey, settings.translationEngine);
82
+ }
83
+
84
+ //#endregion
85
+ exports.createWeglotConfig = createWeglotConfig;
86
+ exports.resolveProjectLanguages = resolveProjectLanguages;
@@ -0,0 +1,83 @@
1
+ import { WeglotApiClient } from "../translators/weglot/api-client.mjs";
2
+ import { resolveTranslationEngine } from "../translators/weglot/engine.mjs";
3
+ import "dotenv/config";
4
+
5
+ //#region src/utils/config-factory.ts
6
+ /**
7
+ * Default configuration values
8
+ */
9
+ const DEFAULT_CONFIG = {
10
+ sourceRoot: "src",
11
+ weglotDir: "weglot",
12
+ useDirective: false,
13
+ translatableAttributes: {},
14
+ dev: { translationServerStartPort: 6e4 },
15
+ localePersistence: {
16
+ type: "cookie",
17
+ config: {
18
+ name: "locale",
19
+ maxAge: 31536e3
20
+ }
21
+ },
22
+ buildMode: "translate"
23
+ };
24
+ /**
25
+ * Create a LoaderConfig with defaults applied
26
+ *
27
+ * @param options - Partial config to override defaults
28
+ * @returns Complete LoaderConfig with all defaults applied
29
+ *
30
+ */
31
+ function createWeglotConfig(options) {
32
+ const cleanOptions = { ...options };
33
+ const cleanObject = (obj) => {
34
+ if (!obj || typeof obj !== "object") return;
35
+ Object.keys(obj).forEach((key) => {
36
+ if (obj[key] === void 0) delete obj[key];
37
+ else if (obj[key] && typeof obj[key] === "object" && !Array.isArray(obj[key])) cleanObject(obj[key]);
38
+ });
39
+ };
40
+ cleanObject(cleanOptions);
41
+ const apiKey = cleanOptions.apiKey ?? process.env.WEGLOT_API_KEY;
42
+ if (!apiKey) throw new Error("Weglot project key is missing. Pass `apiKey` in the plugin options or set the WEGLOT_API_KEY environment variable.");
43
+ return {
44
+ ...DEFAULT_CONFIG,
45
+ ...cleanOptions,
46
+ apiKey,
47
+ sourceLocale: cleanOptions.sourceLocale ?? "",
48
+ targetLocales: cleanOptions.targetLocales ?? [],
49
+ apiLocales: cleanOptions.apiLocales ?? {},
50
+ translationEngine: cleanOptions.translationEngine ?? resolveTranslationEngine(apiKey),
51
+ environment: cleanOptions.environment ?? (process.env.NODE_ENV === "development" ? "development" : "production"),
52
+ cacheType: cleanOptions.cacheType ?? "local",
53
+ dev: {
54
+ ...DEFAULT_CONFIG.dev,
55
+ ...cleanOptions.dev
56
+ },
57
+ localePersistence: {
58
+ ...DEFAULT_CONFIG.localePersistence,
59
+ ...cleanOptions.localePersistence,
60
+ config: {
61
+ ...DEFAULT_CONFIG.localePersistence.config,
62
+ ...cleanOptions.localePersistence?.config
63
+ }
64
+ }
65
+ };
66
+ }
67
+ /**
68
+ * Fetches source/target locales from the Weglot project settings.
69
+ * Idempotent: no-ops when locales are already resolved (e.g. passed
70
+ * through Next.js loader options).
71
+ */
72
+ async function resolveProjectLanguages(config, client = new WeglotApiClient(config.apiKey)) {
73
+ if (config.sourceLocale && config.targetLocales.length > 0) return;
74
+ const settings = await client.fetchSettings();
75
+ config.sourceLocale = settings.sourceLocale;
76
+ config.targetLocales = settings.targetLocales;
77
+ config.apiLocales = settings.apiLocales;
78
+ config.translationEngine = resolveTranslationEngine(config.apiKey, settings.translationEngine);
79
+ }
80
+
81
+ //#endregion
82
+ export { createWeglotConfig, resolveProjectLanguages };
83
+ //# sourceMappingURL=config-factory.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-factory.mjs","names":[],"sources":["../../src/utils/config-factory.ts"],"sourcesContent":["/**\n * Config factory for creating LoaderConfig instances\n */\nimport \"dotenv/config\";\nimport type {\n WeglotConfig,\n WeglotInternalFields,\n PartialWeglotConfig,\n} from \"../types\";\nimport { WeglotApiClient } from \"../translators/weglot/api-client\";\nimport { resolveTranslationEngine } from \"../translators/weglot/engine\";\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONFIG = {\n sourceRoot: \"src\",\n weglotDir: \"weglot\",\n useDirective: false,\n translatableAttributes: {},\n dev: {\n translationServerStartPort: 60000,\n },\n localePersistence: {\n type: \"cookie\" as const,\n config: {\n name: \"locale\",\n maxAge: 31536000,\n },\n },\n buildMode: \"translate\",\n} satisfies Omit<\n WeglotConfig,\n // weglotDir is an internal field for public-config purposes, but (unlike\n // the other internal fields) it still has a static default here rather\n // than being resolved at runtime, so it stays out of this Omit.\n \"apiKey\" | Exclude<WeglotInternalFields, \"weglotDir\">\n>;\n\n/**\n * Create a LoaderConfig with defaults applied\n *\n * @param options - Partial config to override defaults\n * @returns Complete LoaderConfig with all defaults applied\n *\n */\nexport function createWeglotConfig(\n options: PartialWeglotConfig & Partial<Pick<WeglotConfig, WeglotInternalFields>>,\n): WeglotConfig {\n const cleanOptions = { ...options };\n\n const cleanObject = (obj: any) => {\n if (!obj || typeof obj !== \"object\") return;\n Object.keys(obj).forEach((key) => {\n if (obj[key] === undefined) {\n delete obj[key];\n } else if (\n obj[key] &&\n typeof obj[key] === \"object\" &&\n !Array.isArray(obj[key])\n ) {\n cleanObject(obj[key]);\n }\n });\n };\n\n cleanObject(cleanOptions);\n\n const apiKey = cleanOptions.apiKey ?? process.env.WEGLOT_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"Weglot project key is missing. Pass `apiKey` in the plugin options or set the WEGLOT_API_KEY environment variable.\",\n );\n }\n\n return {\n ...DEFAULT_CONFIG,\n ...cleanOptions,\n apiKey,\n sourceLocale: cleanOptions.sourceLocale ?? \"\",\n targetLocales: cleanOptions.targetLocales ?? [],\n apiLocales: cleanOptions.apiLocales ?? {},\n translationEngine:\n cleanOptions.translationEngine ?? resolveTranslationEngine(apiKey),\n environment:\n cleanOptions.environment ??\n (process.env.NODE_ENV === \"development\" ? \"development\" : \"production\"),\n cacheType: cleanOptions.cacheType ?? \"local\",\n dev: {\n ...DEFAULT_CONFIG.dev,\n ...cleanOptions.dev,\n },\n localePersistence: {\n ...DEFAULT_CONFIG.localePersistence,\n ...cleanOptions.localePersistence,\n config: {\n ...DEFAULT_CONFIG.localePersistence.config,\n ...cleanOptions.localePersistence?.config,\n },\n },\n };\n}\n\n/**\n * Fetches source/target locales from the Weglot project settings.\n * Idempotent: no-ops when locales are already resolved (e.g. passed\n * through Next.js loader options).\n */\nexport async function resolveProjectLanguages(\n config: WeglotConfig,\n client: WeglotApiClient = new WeglotApiClient(config.apiKey),\n): Promise<void> {\n if (config.sourceLocale && config.targetLocales.length > 0) {\n return;\n }\n const settings = await client.fetchSettings();\n config.sourceLocale = settings.sourceLocale;\n config.targetLocales = settings.targetLocales;\n config.apiLocales = settings.apiLocales;\n config.translationEngine = resolveTranslationEngine(\n config.apiKey,\n settings.translationEngine,\n );\n}\n"],"mappings":";;;;;;;;AAeA,MAAa,iBAAiB;CAC5B,YAAY;CACZ,WAAW;CACX,cAAc;CACd,wBAAwB,EAAE;CAC1B,KAAK,EACH,4BAA4B,KAC7B;CACD,mBAAmB;EACjB,MAAM;EACN,QAAQ;GACN,MAAM;GACN,QAAQ;GACT;EACF;CACD,WAAW;CACZ;;;;;;;;AAeD,SAAgB,mBACd,SACc;CACd,MAAM,eAAe,EAAE,GAAG,SAAS;CAEnC,MAAM,eAAe,QAAa;AAChC,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU;AACrC,SAAO,KAAK,IAAI,CAAC,SAAS,QAAQ;AAChC,OAAI,IAAI,SAAS,OACf,QAAO,IAAI;YAEX,IAAI,QACJ,OAAO,IAAI,SAAS,YACpB,CAAC,MAAM,QAAQ,IAAI,KAAK,CAExB,aAAY,IAAI,KAAK;IAEvB;;AAGJ,aAAY,aAAa;CAEzB,MAAM,SAAS,aAAa,UAAU,QAAQ,IAAI;AAClD,KAAI,CAAC,OACH,OAAM,IAAI,MACR,qHACD;AAGH,QAAO;EACL,GAAG;EACH,GAAG;EACH;EACA,cAAc,aAAa,gBAAgB;EAC3C,eAAe,aAAa,iBAAiB,EAAE;EAC/C,YAAY,aAAa,cAAc,EAAE;EACzC,mBACE,aAAa,qBAAqB,yBAAyB,OAAO;EACpE,aACE,aAAa,gBACZ,QAAQ,IAAI,aAAa,gBAAgB,gBAAgB;EAC5D,WAAW,aAAa,aAAa;EACrC,KAAK;GACH,GAAG,eAAe;GAClB,GAAG,aAAa;GACjB;EACD,mBAAmB;GACjB,GAAG,eAAe;GAClB,GAAG,aAAa;GAChB,QAAQ;IACN,GAAG,eAAe,kBAAkB;IACpC,GAAG,aAAa,mBAAmB;IACpC;GACF;EACF;;;;;;;AAQH,eAAsB,wBACpB,QACA,SAA0B,IAAI,gBAAgB,OAAO,OAAO,EAC7C;AACf,KAAI,OAAO,gBAAgB,OAAO,cAAc,SAAS,EACvD;CAEF,MAAM,WAAW,MAAM,OAAO,eAAe;AAC7C,QAAO,eAAe,SAAS;AAC/B,QAAO,gBAAgB,SAAS;AAChC,QAAO,aAAa,SAAS;AAC7B,QAAO,oBAAoB,yBACzB,OAAO,QACP,SAAS,kBACV"}
@@ -0,0 +1,17 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ let crypto = require("crypto");
3
+ crypto = require_rolldown_runtime.__toESM(crypto);
4
+
5
+ //#region src/utils/hash.ts
6
+ /**
7
+ * Generate a hash for a translation entry
8
+ * Hash is based on: sourceText + context
9
+ * This ensures that the same text in different components or files gets different hashes
10
+ */
11
+ function generateTranslationHash(sourceText, context) {
12
+ const input = `${sourceText}::${Object.entries(context).sort((a, b) => a[0].localeCompare(b[0])).map(([key, value]) => `${key}:${value}`).join("::")}`;
13
+ return crypto.default.createHash("md5").update(input).digest("hex").substring(0, 12);
14
+ }
15
+
16
+ //#endregion
17
+ exports.generateTranslationHash = generateTranslationHash;
@@ -0,0 +1,16 @@
1
+ import crypto from "crypto";
2
+
3
+ //#region src/utils/hash.ts
4
+ /**
5
+ * Generate a hash for a translation entry
6
+ * Hash is based on: sourceText + context
7
+ * This ensures that the same text in different components or files gets different hashes
8
+ */
9
+ function generateTranslationHash(sourceText, context) {
10
+ const input = `${sourceText}::${Object.entries(context).sort((a, b) => a[0].localeCompare(b[0])).map(([key, value]) => `${key}:${value}`).join("::")}`;
11
+ return crypto.createHash("md5").update(input).digest("hex").substring(0, 12);
12
+ }
13
+
14
+ //#endregion
15
+ export { generateTranslationHash };
16
+ //# sourceMappingURL=hash.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.mjs","names":[],"sources":["../../src/utils/hash.ts"],"sourcesContent":["import crypto from \"crypto\";\n\n/*\n * If we find md5 too slow, we can use FNV-1a\n *\n * function generateHash(text: string): string {\n * let hash = 2166136261;\n * for (let i = 0; i < text.length; i++) {\n * hash ^= text.charCodeAt(i);\n * hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 12);\n * }\n * return (hash >>> 0).toString(36).padStart(7, '0').slice(0, 12);\n * }\n *\n */\n\n/**\n * Generate a hash for a translation entry\n * Hash is based on: sourceText + context\n * This ensures that the same text in different components or files gets different hashes\n */\nexport function generateTranslationHash(\n sourceText: string,\n context: Record<string, any>,\n): string {\n const input = `${sourceText}::${Object.entries(context)\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([key, value]) => `${key}:${value}`)\n .join(\"::\")}`;\n return crypto.createHash(\"md5\").update(input).digest(\"hex\").substring(0, 12); // Use first 12 chars for brevity\n}\n\n/**\n * Validate that a hash matches the expected format\n */\nexport function isValidHash(hash: string): boolean {\n return /^[a-f0-9]{12}$/.test(hash);\n}\n"],"mappings":";;;;;;;;AAqBA,SAAgB,wBACd,YACA,SACQ;CACR,MAAM,QAAQ,GAAG,WAAW,IAAI,OAAO,QAAQ,QAAQ,CACpD,MAAM,GAAG,MAAM,EAAE,GAAG,cAAc,EAAE,GAAG,CAAC,CACxC,KAAK,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,QAAQ,CACxC,KAAK,KAAK;AACb,QAAO,OAAO,WAAW,MAAM,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM,CAAC,UAAU,GAAG,GAAG"}