generaltranslation 8.2.6 → 8.2.8

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 (162) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/ApiError-4zIP-twr.cjs +24 -0
  3. package/dist/ApiError-4zIP-twr.cjs.map +1 -0
  4. package/dist/ApiError-Bv7vlzyQ.mjs +19 -0
  5. package/dist/ApiError-Bv7vlzyQ.mjs.map +1 -0
  6. package/dist/errors.cjs +3 -0
  7. package/dist/errors.d.cts +11 -0
  8. package/dist/errors.d.mts +11 -0
  9. package/dist/errors.mjs +2 -0
  10. package/dist/id-CPbVYREY.mjs +74 -0
  11. package/dist/id-CPbVYREY.mjs.map +1 -0
  12. package/dist/id-VXBgyXu2.cjs +89 -0
  13. package/dist/id-VXBgyXu2.cjs.map +1 -0
  14. package/dist/id.cjs +5 -0
  15. package/dist/{id/hashSource.d.ts → id.d.cts} +20 -5
  16. package/dist/id.d.mts +40 -0
  17. package/dist/id.mjs +2 -0
  18. package/dist/index.cjs +3491 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +1219 -0
  21. package/dist/index.d.mts +1219 -0
  22. package/dist/index.mjs +3441 -0
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/internal-B3QbyI_5.mjs +820 -0
  25. package/dist/internal-B3QbyI_5.mjs.map +1 -0
  26. package/dist/internal-DIHQF9gs.cjs +1070 -0
  27. package/dist/internal-DIHQF9gs.cjs.map +1 -0
  28. package/dist/internal.cjs +45 -0
  29. package/dist/{internal.d.ts → internal.d.cts} +82 -113
  30. package/dist/internal.d.mts +263 -0
  31. package/dist/internal.mjs +3 -0
  32. package/dist/sha2-DKowBr6H.cjs +747 -0
  33. package/dist/sha2-DKowBr6H.cjs.map +1 -0
  34. package/dist/stableStringify-DgDlE_pD.mjs +53 -0
  35. package/dist/stableStringify-DgDlE_pD.mjs.map +1 -0
  36. package/dist/types-BJdoI1d1.d.cts +741 -0
  37. package/dist/types-DazaDJbs.d.mts +741 -0
  38. package/dist/types.cjs +17 -0
  39. package/dist/types.cjs.map +1 -0
  40. package/dist/types.d.cts +2 -0
  41. package/dist/types.d.mts +2 -0
  42. package/dist/types.mjs +16 -0
  43. package/dist/types.mjs.map +1 -0
  44. package/package.json +52 -32
  45. package/dist/backwards-compatability/dataConversion.d.ts +0 -23
  46. package/dist/backwards-compatability/oldHashJsxChildren.d.ts +0 -23
  47. package/dist/backwards-compatability/oldTypes.d.ts +0 -21
  48. package/dist/backwards-compatability/typeChecking.d.ts +0 -21
  49. package/dist/cache/IntlCache.d.ts +0 -26
  50. package/dist/cache/types.d.ts +0 -32
  51. package/dist/derive/condenseVars.d.ts +0 -7
  52. package/dist/derive/declareVar.d.ts +0 -26
  53. package/dist/derive/decodeVars.d.ts +0 -9
  54. package/dist/derive/derive.d.ts +0 -38
  55. package/dist/derive/extractVars.d.ts +0 -9
  56. package/dist/derive/index.d.ts +0 -7
  57. package/dist/derive/indexVars.d.ts +0 -6
  58. package/dist/derive/utils/constants.d.ts +0 -2
  59. package/dist/derive/utils/regex.d.ts +0 -2
  60. package/dist/derive/utils/sanitizeVar.d.ts +0 -12
  61. package/dist/derive/utils/traverseHelpers.d.ts +0 -4
  62. package/dist/derive/utils/traverseIcu.d.ts +0 -20
  63. package/dist/derive/utils/types.d.ts +0 -23
  64. package/dist/errors/ApiError.d.ts +0 -7
  65. package/dist/errors/formattingErrors.d.ts +0 -1
  66. package/dist/errors.cjs.min.cjs +0 -2
  67. package/dist/errors.cjs.min.cjs.map +0 -1
  68. package/dist/errors.d.ts +0 -9
  69. package/dist/errors.esm.min.mjs +0 -2
  70. package/dist/errors.esm.min.mjs.map +0 -1
  71. package/dist/formatting/custom-formats/CutoffFormat/CutoffFormat.d.ts +0 -59
  72. package/dist/formatting/custom-formats/CutoffFormat/constants.d.ts +0 -4
  73. package/dist/formatting/custom-formats/CutoffFormat/types.d.ts +0 -48
  74. package/dist/formatting/format.d.ts +0 -1
  75. package/dist/id/hashTemplate.d.ts +0 -4
  76. package/dist/id/types.d.ts +0 -7
  77. package/dist/id.cjs.min.cjs +0 -2
  78. package/dist/id.cjs.min.cjs.map +0 -1
  79. package/dist/id.d.ts +0 -86
  80. package/dist/id.esm.min.mjs +0 -2
  81. package/dist/id.esm.min.mjs.map +0 -1
  82. package/dist/index.cjs.min.cjs +0 -2
  83. package/dist/index.cjs.min.cjs.map +0 -1
  84. package/dist/index.d.ts +0 -1627
  85. package/dist/index.esm.min.mjs +0 -2
  86. package/dist/index.esm.min.mjs.map +0 -1
  87. package/dist/internal.cjs.min.cjs +0 -2
  88. package/dist/internal.cjs.min.cjs.map +0 -1
  89. package/dist/internal.esm.min.mjs +0 -2
  90. package/dist/internal.esm.min.mjs.map +0 -1
  91. package/dist/locales/customLocaleMapping.d.ts +0 -11
  92. package/dist/locales/determineLocale.d.ts +0 -1
  93. package/dist/locales/getLocaleDirection.d.ts +0 -1
  94. package/dist/locales/getLocaleEmoji.d.ts +0 -2
  95. package/dist/locales/getLocaleName.d.ts +0 -1
  96. package/dist/locales/getLocaleProperties.d.ts +0 -32
  97. package/dist/locales/getPluralForm.d.ts +0 -9
  98. package/dist/locales/getRegionProperties.d.ts +0 -7
  99. package/dist/locales/isSameDialect.d.ts +0 -1
  100. package/dist/locales/isSameLanguage.d.ts +0 -1
  101. package/dist/locales/isSupersetLocale.d.ts +0 -1
  102. package/dist/locales/isValidLocale.d.ts +0 -1
  103. package/dist/locales/requiresTranslation.d.ts +0 -1
  104. package/dist/locales/resolveAliasLocale.d.ts +0 -8
  105. package/dist/locales/resolveCanonicalLocale.d.ts +0 -8
  106. package/dist/logging/errors.d.ts +0 -10
  107. package/dist/logging/logger.d.ts +0 -117
  108. package/dist/logging/warnings.d.ts +0 -2
  109. package/dist/projects/getProjectData.d.ts +0 -1
  110. package/dist/settings/plurals.d.ts +0 -3
  111. package/dist/settings/settings.d.ts +0 -2
  112. package/dist/settings/settingsUrls.d.ts +0 -3
  113. package/dist/translate/api.d.ts +0 -1
  114. package/dist/translate/awaitJobs.d.ts +0 -19
  115. package/dist/translate/checkJobStatus.d.ts +0 -8
  116. package/dist/translate/createBranch.d.ts +0 -10
  117. package/dist/translate/createTag.d.ts +0 -19
  118. package/dist/translate/downloadFileBatch.d.ts +0 -1
  119. package/dist/translate/enqueueFiles.d.ts +0 -8
  120. package/dist/translate/getOrphanedFiles.d.ts +0 -8
  121. package/dist/translate/processFileMoves.d.ts +0 -25
  122. package/dist/translate/publishFiles.d.ts +0 -17
  123. package/dist/translate/queryBranchData.d.ts +0 -3
  124. package/dist/translate/queryFileData.d.ts +0 -42
  125. package/dist/translate/querySourceFile.d.ts +0 -1
  126. package/dist/translate/setupProject.d.ts +0 -11
  127. package/dist/translate/submitUserEditDiffs.d.ts +0 -12
  128. package/dist/translate/translateMany.d.ts +0 -1
  129. package/dist/translate/uploadSourceFiles.d.ts +0 -1
  130. package/dist/translate/uploadTranslations.d.ts +0 -1
  131. package/dist/translate/utils/apiRequest.d.ts +0 -1
  132. package/dist/translate/utils/batch.d.ts +0 -52
  133. package/dist/translate/utils/fetchWithTimeout.d.ts +0 -1
  134. package/dist/translate/utils/generateRequestHeaders.d.ts +0 -2
  135. package/dist/translate/utils/handleFetchError.d.ts +0 -1
  136. package/dist/translate/utils/validateResponse.d.ts +0 -1
  137. package/dist/types-dir/api/branch.d.ts +0 -10
  138. package/dist/types-dir/api/checkFileTranslations.d.ts +0 -37
  139. package/dist/types-dir/api/downloadFile.d.ts +0 -3
  140. package/dist/types-dir/api/downloadFileBatch.d.ts +0 -34
  141. package/dist/types-dir/api/enqueueEntries.d.ts +0 -21
  142. package/dist/types-dir/api/enqueueFiles.d.ts +0 -56
  143. package/dist/types-dir/api/entry.d.ts +0 -36
  144. package/dist/types-dir/api/fetchTranslations.d.ts +0 -11
  145. package/dist/types-dir/api/file.d.ts +0 -54
  146. package/dist/types-dir/api/project.d.ts +0 -7
  147. package/dist/types-dir/api/translate.d.ts +0 -34
  148. package/dist/types-dir/api/translateMany.d.ts +0 -5
  149. package/dist/types-dir/api/translationStatus.d.ts +0 -9
  150. package/dist/types-dir/api/uploadFiles.d.ts +0 -43
  151. package/dist/types-dir/jsx/content.d.ts +0 -61
  152. package/dist/types-dir/jsx/variables.d.ts +0 -9
  153. package/dist/types-dir/transformations.d.ts +0 -8
  154. package/dist/types.cjs.min.cjs +0 -2
  155. package/dist/types.cjs.min.cjs.map +0 -1
  156. package/dist/types.d.ts +0 -652
  157. package/dist/types.esm.min.mjs +0 -2
  158. package/dist/types.esm.min.mjs.map +0 -1
  159. package/dist/utils/base64.d.ts +0 -2
  160. package/dist/utils/isVariable.d.ts +0 -2
  161. package/dist/utils/minify.d.ts +0 -2
  162. package/dist/utils/stableStringify.d.ts +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,3441 @@
1
+ import { B as intlCache, M as encode, V as defaultTimeout, j as decode, k as validateFileFormatTransforms } from "./internal-B3QbyI_5.mjs";
2
+ import { t as ApiError } from "./ApiError-Bv7vlzyQ.mjs";
3
+ import { n as hashSource } from "./id-CPbVYREY.mjs";
4
+ import IntlMessageFormat from "intl-messageformat";
5
+ //#region src/locales/isValidLocale.ts
6
+ const scriptExceptions = [
7
+ "Cham",
8
+ "Jamo",
9
+ "Kawi",
10
+ "Lisu",
11
+ "Toto",
12
+ "Thai"
13
+ ];
14
+ const isCustomLanguage = (language) => {
15
+ return language >= "qaa" && language <= "qtz";
16
+ };
17
+ /**
18
+ * Checks if a given BCP 47 language code is valid.
19
+ * @param {string} code - The BCP 47 language code to validate.
20
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for validation.
21
+ * @returns {boolean} True if the BCP 47 code is valid, false otherwise.
22
+ * @internal
23
+ */
24
+ const _isValidLocale = (locale, customMapping) => {
25
+ if (customMapping?.[locale] && typeof customMapping[locale] === "object" && "code" in customMapping[locale] && customMapping[locale].code) locale = customMapping[locale].code;
26
+ try {
27
+ const { language, region, script } = intlCache.get("Locale", locale);
28
+ if (locale.split("-").length !== (() => {
29
+ let partCount = 1;
30
+ if (region) partCount += 1;
31
+ if (script) partCount += 1;
32
+ return partCount;
33
+ })()) return false;
34
+ if (intlCache.get("DisplayNames", ["en"], { type: "language" }).of(language) === language && !isCustomLanguage(language)) return false;
35
+ if (region) {
36
+ if (intlCache.get("DisplayNames", ["en"], { type: "region" }).of(region) === region) return false;
37
+ }
38
+ if (script) {
39
+ if (intlCache.get("DisplayNames", ["en"], { type: "script" }).of(script) === script && !scriptExceptions.includes(script)) return false;
40
+ }
41
+ return true;
42
+ } catch {
43
+ return false;
44
+ }
45
+ };
46
+ /**
47
+ * Standardizes a BCP 47 locale to ensure correct formatting.
48
+ * @param {string} locale - The BCP 47 locale to standardize.
49
+ * @returns {string} The standardized BCP 47 locale, or an empty string if invalid.
50
+ * @internal
51
+ */
52
+ const _standardizeLocale = (locale) => {
53
+ try {
54
+ return Intl.getCanonicalLocales(locale)[0];
55
+ } catch {
56
+ return locale;
57
+ }
58
+ };
59
+ //#endregion
60
+ //#region src/locales/isSameDialect.ts
61
+ function checkTwoLocalesAreSameDialect(codeA, codeB) {
62
+ const { language: languageA, region: regionA, script: scriptA } = intlCache.get("Locale", codeA);
63
+ const { language: languageB, region: regionB, script: scriptB } = intlCache.get("Locale", codeB);
64
+ if (languageA !== languageB) return false;
65
+ if (regionA && regionB && regionA !== regionB) return false;
66
+ if (scriptA && scriptB && scriptA !== scriptB) return false;
67
+ return true;
68
+ }
69
+ /**
70
+ * Test two or more language codes to determine if they are exactly the same
71
+ * e.g. "en-US" and "en" would be exactly the same.
72
+ * "en-GB" and "en" would be exactly the same.
73
+ * "en-GB" and "en-US" would be different.
74
+ * @internal
75
+ */
76
+ function _isSameDialect(...locales) {
77
+ try {
78
+ const flattenedCodes = locales.flat().map(_standardizeLocale);
79
+ for (let i = 0; i < flattenedCodes.length; i++) for (let j = i + 1; j < flattenedCodes.length; j++) if (!checkTwoLocalesAreSameDialect(flattenedCodes[i], flattenedCodes[j])) return false;
80
+ return true;
81
+ } catch (error) {
82
+ console.error(error);
83
+ return false;
84
+ }
85
+ }
86
+ //#endregion
87
+ //#region src/locales/isSameLanguage.ts
88
+ /**
89
+ * @internal
90
+ */
91
+ function _isSameLanguage(...locales) {
92
+ try {
93
+ const languages = locales.flat().map((locale) => intlCache.get("Locale", locale).language);
94
+ return languages.every((language) => language === languages[0]);
95
+ } catch (error) {
96
+ console.error(error);
97
+ return false;
98
+ }
99
+ }
100
+ //#endregion
101
+ //#region src/locales/requiresTranslation.ts
102
+ /**
103
+ * Given a target locale and a source locale, determines whether a translation is required
104
+ * If the target locale and the source locale are the same, returns false, otherwise returns true
105
+ * If a translation is not possible due to the target locale being outside of the optional approvedLanguages scope, also returns false
106
+ * @internal
107
+ */
108
+ function _requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping) {
109
+ if (!_isValidLocale(sourceLocale, customMapping) || !_isValidLocale(targetLocale, customMapping) || approvedLocales && approvedLocales.some((approvedLocale) => !_isValidLocale(approvedLocale, customMapping))) return false;
110
+ if (_isSameDialect(sourceLocale, targetLocale)) return false;
111
+ if (approvedLocales && !approvedLocales.some((approvedLocale) => _isSameLanguage(targetLocale, approvedLocale))) return false;
112
+ return true;
113
+ }
114
+ //#endregion
115
+ //#region src/locales/customLocaleMapping.ts
116
+ const getCustomProperty = (customMapping, locale, property) => {
117
+ if (customMapping?.[locale]) {
118
+ if (typeof customMapping[locale] === "string") return property === "name" ? customMapping[locale] : void 0;
119
+ return customMapping[locale][property];
120
+ }
121
+ };
122
+ /**
123
+ * Checks if a given locale should use the canonical locale.
124
+ * @param locale - The locale to check if it should use the canonical locale
125
+ * @param customMapping - The custom mapping to use for checking if the locale should use the canonical locale
126
+ * @returns True if the locale should use the canonical locale, false otherwise
127
+ */
128
+ const shouldUseCanonicalLocale = (locale, customMapping) => {
129
+ return !!(customMapping?.[locale] && typeof customMapping[locale] === "object" && "code" in customMapping[locale] && customMapping[locale].code && _isValidLocale(customMapping[locale].code));
130
+ };
131
+ //#endregion
132
+ //#region src/locales/getLocaleEmoji.ts
133
+ /**
134
+ * @internal
135
+ */
136
+ function _getLocaleEmoji(locale, customMapping) {
137
+ const aliasedLocale = locale;
138
+ if (customMapping && shouldUseCanonicalLocale(locale, customMapping)) locale = customMapping[locale].code;
139
+ try {
140
+ const standardizedLocale = _standardizeLocale(locale);
141
+ const localeObject = intlCache.get("Locale", standardizedLocale);
142
+ const { language, region } = localeObject;
143
+ if (customMapping) for (const l of [
144
+ aliasedLocale,
145
+ locale,
146
+ standardizedLocale,
147
+ language
148
+ ]) {
149
+ const customEmoji = getCustomProperty(customMapping, l, "emoji");
150
+ if (customEmoji) return customEmoji;
151
+ }
152
+ if (region && emojis[region]) return emojis[region];
153
+ const extrapolated = localeObject.maximize();
154
+ const extrapolatedRegion = extrapolated.region || "";
155
+ return exceptions[extrapolated.language] || emojis[extrapolatedRegion] || "🌍";
156
+ } catch {
157
+ return defaultEmoji;
158
+ }
159
+ }
160
+ const europeAfricaGlobe = "🌍";
161
+ const asiaAustraliaGlobe = "🌏";
162
+ const defaultEmoji = europeAfricaGlobe;
163
+ const exceptions = {
164
+ ca: europeAfricaGlobe,
165
+ eu: europeAfricaGlobe,
166
+ ku: europeAfricaGlobe,
167
+ bo: asiaAustraliaGlobe,
168
+ ug: asiaAustraliaGlobe,
169
+ gd: "🏴󠁧󠁢󠁳󠁣󠁴󠁿",
170
+ cy: "🏴󠁧󠁢󠁷󠁬󠁳󠁿",
171
+ gv: "🇮🇲",
172
+ grc: "🏺"
173
+ };
174
+ const emojis = {
175
+ AF: "🇦🇫",
176
+ AX: "🇦🇽",
177
+ AL: "🇦🇱",
178
+ DZ: "🇩🇿",
179
+ AS: "🇦🇸",
180
+ AD: "🇦🇩",
181
+ AO: "🇦🇴",
182
+ AI: "🇦🇮",
183
+ AQ: "🇦🇶",
184
+ AG: "🇦🇬",
185
+ AR: "🇦🇷",
186
+ AM: "🇦🇲",
187
+ AW: "🇦🇼",
188
+ AU: "🇦🇺",
189
+ AT: "🇦🇹",
190
+ AZ: "🇦🇿",
191
+ BS: "🇧🇸",
192
+ BH: "🇧🇭",
193
+ BD: "🇧🇩",
194
+ BB: "🇧🇧",
195
+ BY: "🇧🇾",
196
+ BE: "🇧🇪",
197
+ BZ: "🇧🇿",
198
+ BJ: "🇧🇯",
199
+ BM: "🇧🇲",
200
+ BT: "🇧🇹",
201
+ BO: "🇧🇴",
202
+ BQ: "🇧🇶",
203
+ BA: "🇧🇦",
204
+ BW: "🇧🇼",
205
+ BV: "🇧🇻",
206
+ BR: "🇧🇷",
207
+ IO: "🇮🇴",
208
+ BN: "🇧🇳",
209
+ BG: "🇧🇬",
210
+ BF: "🇧🇫",
211
+ BI: "🇧🇮",
212
+ CV: "🇨🇻",
213
+ KH: "🇰🇭",
214
+ CM: "🇨🇲",
215
+ CA: "🇨🇦",
216
+ KY: "🇰🇾",
217
+ CF: "🇨🇫",
218
+ TD: "🇹🇩",
219
+ CL: "🇨🇱",
220
+ CN: "🇨🇳",
221
+ CX: "🇨🇽",
222
+ CC: "🇨🇨",
223
+ CO: "🇨🇴",
224
+ KM: "🇰🇲",
225
+ CD: "🇨🇩",
226
+ CG: "🇨🇬",
227
+ CK: "🇨🇰",
228
+ CR: "🇨🇷",
229
+ CI: "🇨🇮",
230
+ HR: "🇭🇷",
231
+ CU: "🇨🇺",
232
+ CW: "🇨🇼",
233
+ CY: "🇨🇾",
234
+ CZ: "🇨🇿",
235
+ DK: "🇩🇰",
236
+ DJ: "🇩🇯",
237
+ DM: "🇩🇲",
238
+ DO: "🇩🇴",
239
+ EC: "🇪🇨",
240
+ EG: "🇪🇬",
241
+ SV: "🇸🇻",
242
+ GQ: "🇬🇶",
243
+ ER: "🇪🇷",
244
+ EE: "🇪🇪",
245
+ SZ: "🇸🇿",
246
+ ET: "🇪🇹",
247
+ FK: "🇫🇰",
248
+ FO: "🇫🇴",
249
+ FJ: "🇫🇯",
250
+ FI: "🇫🇮",
251
+ FR: "🇫🇷",
252
+ GF: "🇬🇫",
253
+ PF: "🇵🇫",
254
+ TF: "🇹🇫",
255
+ GA: "🇬🇦",
256
+ GM: "🇬🇲",
257
+ GE: "🇬🇪",
258
+ DE: "🇩🇪",
259
+ GH: "🇬🇭",
260
+ GI: "🇬🇮",
261
+ GR: "🇬🇷",
262
+ GL: "🇬🇱",
263
+ GD: "🇬🇩",
264
+ GP: "🇬🇵",
265
+ GU: "🇬🇺",
266
+ GT: "🇬🇹",
267
+ GG: "🇬🇬",
268
+ GN: "🇬🇳",
269
+ GW: "🇬🇼",
270
+ GY: "🇬🇾",
271
+ HT: "🇭🇹",
272
+ HM: "🇭🇲",
273
+ VA: "🇻🇦",
274
+ HN: "🇭🇳",
275
+ HK: "🇭🇰",
276
+ HU: "🇭🇺",
277
+ IS: "🇮🇸",
278
+ IN: "🇮🇳",
279
+ ID: "🇮🇩",
280
+ IR: "🇮🇷",
281
+ IQ: "🇮🇶",
282
+ IE: "🇮🇪",
283
+ IM: "🇮🇲",
284
+ IL: "🇮🇱",
285
+ IT: "🇮🇹",
286
+ JM: "🇯🇲",
287
+ JP: "🇯🇵",
288
+ JE: "🇯🇪",
289
+ JO: "🇯🇴",
290
+ KZ: "🇰🇿",
291
+ KE: "🇰🇪",
292
+ KI: "🇰🇮",
293
+ KP: "🇰🇵",
294
+ KR: "🇰🇷",
295
+ KW: "🇰🇼",
296
+ KG: "🇰🇬",
297
+ LA: "🇱🇦",
298
+ LV: "🇱🇻",
299
+ LB: "🇱🇧",
300
+ LS: "🇱🇸",
301
+ LR: "🇱🇷",
302
+ LY: "🇱🇾",
303
+ LI: "🇱🇮",
304
+ LT: "🇱🇹",
305
+ LU: "🇱🇺",
306
+ MO: "🇲🇴",
307
+ MG: "🇲🇬",
308
+ MW: "🇲🇼",
309
+ MY: "🇲🇾",
310
+ MV: "🇲🇻",
311
+ ML: "🇲🇱",
312
+ MT: "🇲🇹",
313
+ MH: "🇲🇭",
314
+ MQ: "🇲🇶",
315
+ MR: "🇲🇷",
316
+ MU: "🇲🇺",
317
+ YT: "🇾🇹",
318
+ MX: "🇲🇽",
319
+ FM: "🇫🇲",
320
+ MD: "🇲🇩",
321
+ MC: "🇲🇨",
322
+ MN: "🇲🇳",
323
+ ME: "🇲🇪",
324
+ MS: "🇲🇸",
325
+ MA: "🇲🇦",
326
+ MZ: "🇲🇿",
327
+ MM: "🇲🇲",
328
+ NA: "🇳🇦",
329
+ NR: "🇳🇷",
330
+ NP: "🇳🇵",
331
+ NL: "🇳🇱",
332
+ NC: "🇳🇨",
333
+ NZ: "🇳🇿",
334
+ NI: "🇳🇮",
335
+ NE: "🇳🇪",
336
+ NG: "🇳🇬",
337
+ NU: "🇳🇺",
338
+ NF: "🇳🇫",
339
+ MK: "🇲🇰",
340
+ MP: "🇲🇵",
341
+ NO: "🇳🇴",
342
+ OM: "🇴🇲",
343
+ PK: "🇵🇰",
344
+ PW: "🇵🇼",
345
+ PS: "🇵🇸",
346
+ PA: "🇵🇦",
347
+ PG: "🇵🇬",
348
+ PY: "🇵🇾",
349
+ PE: "🇵🇪",
350
+ PH: "🇵🇭",
351
+ PN: "🇵🇳",
352
+ PL: "🇵🇱",
353
+ PT: "🇵🇹",
354
+ PR: "🇵🇷",
355
+ QA: "🇶🇦",
356
+ RE: "🇷🇪",
357
+ RO: "🇷🇴",
358
+ RU: "🇷🇺",
359
+ RW: "🇷🇼",
360
+ BL: "🇧🇱",
361
+ SH: "🇸🇭",
362
+ KN: "🇰🇳",
363
+ LC: "🇱🇨",
364
+ MF: "🇲🇫",
365
+ PM: "🇵🇲",
366
+ VC: "🇻🇨",
367
+ WS: "🇼🇸",
368
+ SM: "🇸🇲",
369
+ ST: "🇸🇹",
370
+ SA: "🇸🇦",
371
+ SN: "🇸🇳",
372
+ RS: "🇷🇸",
373
+ SC: "🇸🇨",
374
+ SL: "🇸🇱",
375
+ SG: "🇸🇬",
376
+ SX: "🇸🇽",
377
+ SK: "🇸🇰",
378
+ SI: "🇸🇮",
379
+ SB: "🇸🇧",
380
+ SO: "🇸🇴",
381
+ ZA: "🇿🇦",
382
+ GS: "🇬🇸",
383
+ SS: "🇸🇸",
384
+ ES: "🇪🇸",
385
+ LK: "🇱🇰",
386
+ SD: "🇸🇩",
387
+ SR: "🇸🇷",
388
+ SJ: "🇸🇯",
389
+ SE: "🇸🇪",
390
+ CH: "🇨🇭",
391
+ SY: "🇸🇾",
392
+ TW: "🇹🇼",
393
+ TJ: "🇹🇯",
394
+ TZ: "🇹🇿",
395
+ TH: "🇹🇭",
396
+ TL: "🇹🇱",
397
+ TG: "🇹🇬",
398
+ TK: "🇹🇰",
399
+ TO: "🇹🇴",
400
+ TT: "🇹🇹",
401
+ TN: "🇹🇳",
402
+ TR: "🇹🇷",
403
+ TM: "🇹🇲",
404
+ TC: "🇹🇨",
405
+ TV: "🇹🇻",
406
+ UG: "🇺🇬",
407
+ UA: "🇺🇦",
408
+ AE: "🇦🇪",
409
+ GB: "🇬🇧",
410
+ US: "🇺🇸",
411
+ UM: "🇺🇲",
412
+ UY: "🇺🇾",
413
+ UZ: "🇺🇿",
414
+ VU: "🇻🇺",
415
+ VE: "🇻🇪",
416
+ VN: "🇻🇳",
417
+ VG: "🇻🇬",
418
+ VI: "🇻🇮",
419
+ WF: "🇼🇫",
420
+ EH: "🇪🇭",
421
+ YE: "🇾🇪",
422
+ ZM: "🇿🇲",
423
+ ZW: "🇿🇼",
424
+ EU: "🇪🇺",
425
+ "419": "🌎"
426
+ };
427
+ //#endregion
428
+ //#region src/locales/getLocaleProperties.ts
429
+ /**
430
+ * Creates a set of custom locale properties from a custom mapping.
431
+ *
432
+ * @param lArray - An array of locale codes to search for in the custom mapping.
433
+ * @param customMapping - Optional custom mapping of locale codes to names.
434
+ * @returns A partial set of locale properties, or undefined if no custom mapping is provided.
435
+ */
436
+ function createCustomLocaleProperties(lArray, customMapping) {
437
+ if (customMapping) {
438
+ let merged = {};
439
+ for (const l of lArray) {
440
+ const value = customMapping[l];
441
+ if (value) {
442
+ if (typeof value === "string") merged.name ||= value;
443
+ else if (value) merged = {
444
+ ...value,
445
+ ...merged
446
+ };
447
+ }
448
+ }
449
+ return merged;
450
+ }
451
+ }
452
+ /**
453
+ * @internal
454
+ */
455
+ function _getLocaleProperties(locale, defaultLocale = "en", customMapping) {
456
+ const aliasedLocale = locale;
457
+ if (customMapping && shouldUseCanonicalLocale(locale, customMapping)) locale = customMapping[locale].code;
458
+ defaultLocale ||= "en";
459
+ try {
460
+ const standardizedLocale = _standardizeLocale(locale);
461
+ const localeObject = intlCache.get("Locale", locale);
462
+ const languageCode = localeObject.language;
463
+ const customLocaleProperties = createCustomLocaleProperties([
464
+ aliasedLocale,
465
+ locale,
466
+ standardizedLocale,
467
+ languageCode
468
+ ], customMapping);
469
+ const baseRegion = localeObject.region;
470
+ const maximizedLocale = localeObject.maximize();
471
+ const maximizedCode = maximizedLocale.toString();
472
+ const regionCode = localeObject.region || customLocaleProperties?.regionCode || maximizedLocale.region || "";
473
+ const scriptCode = localeObject.script || customLocaleProperties?.scriptCode || maximizedLocale.script || "";
474
+ const minimizedCode = localeObject.minimize().toString();
475
+ const defaultLanguageOrder = [
476
+ defaultLocale,
477
+ locale,
478
+ "en"
479
+ ];
480
+ const nativeLanguageOrder = [
481
+ locale,
482
+ defaultLocale,
483
+ "en"
484
+ ];
485
+ const languageNames = intlCache.get("DisplayNames", defaultLanguageOrder, { type: "language" });
486
+ const nativeLanguageNames = intlCache.get("DisplayNames", nativeLanguageOrder, { type: "language" });
487
+ const customName = customLocaleProperties?.name;
488
+ const customNativeName = customLocaleProperties?.nativeName || customLocaleProperties?.name;
489
+ const name = customName || languageNames.of(locale) || locale;
490
+ const nativeName = customNativeName || nativeLanguageNames.of(locale) || locale;
491
+ const maximizedName = customLocaleProperties?.maximizedName || customName || languageNames.of(maximizedCode) || locale;
492
+ const nativeMaximizedName = customLocaleProperties?.nativeMaximizedName || customNativeName || nativeLanguageNames.of(maximizedCode) || locale;
493
+ const minimizedName = customLocaleProperties?.minimizedName || customName || languageNames.of(minimizedCode) || locale;
494
+ const nativeMinimizedName = customLocaleProperties?.nativeMinimizedName || customNativeName || nativeLanguageNames.of(minimizedCode) || locale;
495
+ const languageName = customLocaleProperties?.languageName || customName || languageNames.of(languageCode) || locale;
496
+ const nativeLanguageName = customLocaleProperties?.nativeLanguageName || customNativeName || nativeLanguageNames.of(languageCode) || locale;
497
+ const nameWithRegionCode = customLocaleProperties?.nameWithRegionCode || baseRegion ? `${languageName} (${baseRegion})` : name;
498
+ const nativeNameWithRegionCode = customLocaleProperties?.nativeNameWithRegionCode || (baseRegion ? `${nativeLanguageName} (${baseRegion})` : nativeName) || nameWithRegionCode;
499
+ const regionNames = intlCache.get("DisplayNames", defaultLanguageOrder, { type: "region" });
500
+ const nativeRegionNames = intlCache.get("DisplayNames", nativeLanguageOrder, { type: "region" });
501
+ const regionName = customLocaleProperties?.regionName || (regionCode ? regionNames.of(regionCode) : "") || "";
502
+ const nativeRegionName = customLocaleProperties?.nativeRegionName || (regionCode ? nativeRegionNames.of(regionCode) : "") || "";
503
+ const scriptNames = intlCache.get("DisplayNames", defaultLanguageOrder, { type: "script" });
504
+ const nativeScriptNames = intlCache.get("DisplayNames", nativeLanguageOrder, { type: "script" });
505
+ return {
506
+ code: standardizedLocale,
507
+ name,
508
+ nativeName,
509
+ maximizedCode,
510
+ maximizedName,
511
+ nativeMaximizedName,
512
+ minimizedCode,
513
+ minimizedName,
514
+ nativeMinimizedName,
515
+ languageCode,
516
+ languageName,
517
+ nativeLanguageName,
518
+ nameWithRegionCode,
519
+ nativeNameWithRegionCode,
520
+ regionCode,
521
+ regionName,
522
+ nativeRegionName,
523
+ scriptCode,
524
+ scriptName: customLocaleProperties?.scriptName || (scriptCode ? scriptNames.of(scriptCode) : "") || "",
525
+ nativeScriptName: customLocaleProperties?.nativeScriptName || (scriptCode ? nativeScriptNames.of(scriptCode) : "") || "",
526
+ emoji: customLocaleProperties?.emoji || _getLocaleEmoji(standardizedLocale, customMapping)
527
+ };
528
+ } catch {
529
+ let code = _isValidLocale(locale) ? _standardizeLocale(locale) : locale;
530
+ const codeParts = code?.split("-");
531
+ let languageCode = codeParts?.[0] || code || "";
532
+ let regionCode = codeParts.length > 2 ? codeParts?.[2] : codeParts?.[1] || "";
533
+ let scriptCode = codeParts?.[3] || "";
534
+ const customLocaleProperties = createCustomLocaleProperties([code, languageCode], customMapping);
535
+ code = customLocaleProperties?.code || code;
536
+ const name = customLocaleProperties?.name || code;
537
+ const nativeName = customLocaleProperties?.nativeName || name;
538
+ const maximizedCode = customLocaleProperties?.maximizedCode || code;
539
+ const maximizedName = customLocaleProperties?.maximizedName || name;
540
+ const nativeMaximizedName = customLocaleProperties?.nativeMaximizedName || nativeName;
541
+ const minimizedCode = customLocaleProperties?.minimizedCode || code;
542
+ const minimizedName = customLocaleProperties?.minimizedName || name;
543
+ const nativeMinimizedName = customLocaleProperties?.nativeMinimizedName || nativeName;
544
+ languageCode = customLocaleProperties?.languageCode || languageCode;
545
+ const languageName = customLocaleProperties?.languageName || name;
546
+ const nativeLanguageName = customLocaleProperties?.nativeLanguageName || nativeName;
547
+ regionCode = customLocaleProperties?.regionCode || regionCode;
548
+ const regionName = customLocaleProperties?.regionName || "";
549
+ const nativeRegionName = customLocaleProperties?.nativeRegionName || "";
550
+ scriptCode = customLocaleProperties?.scriptCode || scriptCode;
551
+ const scriptName = customLocaleProperties?.scriptName || "";
552
+ const nativeScriptName = customLocaleProperties?.nativeScriptName || "";
553
+ const nameWithRegionCode = customLocaleProperties?.nameWithRegionCode || (regionName ? `${languageName} (${regionName})` : name);
554
+ const nativeNameWithRegionCode = customLocaleProperties?.nativeNameWithRegionCode || (nativeRegionName ? `${nativeLanguageName} (${nativeRegionName})` : nativeName);
555
+ const emoji = customLocaleProperties?.emoji || "🌍";
556
+ return {
557
+ code,
558
+ name,
559
+ nativeName,
560
+ maximizedCode,
561
+ maximizedName,
562
+ nativeMaximizedName,
563
+ minimizedCode,
564
+ minimizedName,
565
+ nativeMinimizedName,
566
+ languageCode,
567
+ languageName,
568
+ nativeLanguageName,
569
+ nameWithRegionCode,
570
+ nativeNameWithRegionCode,
571
+ regionCode,
572
+ regionName,
573
+ nativeRegionName,
574
+ scriptCode,
575
+ scriptName,
576
+ nativeScriptName,
577
+ emoji
578
+ };
579
+ }
580
+ }
581
+ //#endregion
582
+ //#region src/locales/determineLocale.ts
583
+ /**
584
+ * Given a list of locales and a list of approved locales, sorted in preference order
585
+ * Determines which locale is the best match among the approved locales, prioritizing exact matches and falling back to dialects of the same language
586
+ * @internal
587
+ */
588
+ function _determineLocale(locales, approvedLocales, customMapping) {
589
+ if (typeof locales === "string") locales = [locales];
590
+ locales = locales.filter((locale) => _isValidLocale(locale, customMapping)).map(_standardizeLocale);
591
+ approvedLocales = approvedLocales.filter((locale) => _isValidLocale(locale, customMapping)).map(_standardizeLocale);
592
+ for (const locale of locales) {
593
+ const candidates = approvedLocales.filter((approvedLocale) => _isSameLanguage(locale, approvedLocale));
594
+ const getMatchingCode = ({ locale, languageCode, minimizedCode, regionCode, scriptCode }) => {
595
+ const locales = [
596
+ locale,
597
+ `${languageCode}-${regionCode}`,
598
+ `${languageCode}-${scriptCode}`,
599
+ minimizedCode
600
+ ];
601
+ for (const l of locales) if (candidates.includes(l)) return l;
602
+ return null;
603
+ };
604
+ const { languageCode, ...codes } = _getLocaleProperties(locale);
605
+ const matchingCode = getMatchingCode({
606
+ locale,
607
+ languageCode,
608
+ ...codes
609
+ }) || getMatchingCode({
610
+ locale: languageCode,
611
+ ..._getLocaleProperties(languageCode)
612
+ });
613
+ if (matchingCode) return matchingCode;
614
+ }
615
+ }
616
+ //#endregion
617
+ //#region src/logging/logger.ts
618
+ const LOG_LEVELS = {
619
+ debug: 0,
620
+ info: 1,
621
+ warn: 2,
622
+ error: 3,
623
+ off: 4
624
+ };
625
+ const LOG_COLORS = {
626
+ debug: "\x1B[36m",
627
+ info: "\x1B[32m",
628
+ warn: "\x1B[33m",
629
+ error: "\x1B[31m",
630
+ off: ""
631
+ };
632
+ const RESET_COLOR = "\x1B[0m";
633
+ /**
634
+ * Get the configured log level from environment variable or default to 'warn'
635
+ */
636
+ function getConfiguredLogLevel() {
637
+ if (typeof process !== "undefined" && process.env?._GT_LOG_LEVEL) {
638
+ const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();
639
+ if (envLevel in LOG_LEVELS) return envLevel;
640
+ }
641
+ return "warn";
642
+ }
643
+ /**
644
+ * Console log handler that outputs formatted messages to console
645
+ */
646
+ var ConsoleLogHandler = class {
647
+ constructor(config) {
648
+ this.config = config;
649
+ }
650
+ handle(entry) {
651
+ const parts = [];
652
+ if (this.config.includeTimestamp) parts.push(`[${entry.timestamp.toISOString()}]`);
653
+ const colorCode = LOG_COLORS[entry.level];
654
+ const levelText = `[${entry.level.toUpperCase()}]`;
655
+ parts.push(`${colorCode}${levelText}${RESET_COLOR}`);
656
+ if (this.config.prefix) parts.push(`[${this.config.prefix}]`);
657
+ if (this.config.includeContext && entry.context) parts.push(`[${entry.context}]`);
658
+ parts.push(entry.message);
659
+ if (entry.metadata && Object.keys(entry.metadata).length > 0) parts.push(`\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);
660
+ const formattedMessage = parts.join(" ");
661
+ switch (entry.level) {
662
+ case "debug":
663
+ console.debug(formattedMessage);
664
+ break;
665
+ case "info":
666
+ console.info(formattedMessage);
667
+ break;
668
+ case "warn":
669
+ console.warn(formattedMessage);
670
+ break;
671
+ case "error":
672
+ console.error(formattedMessage);
673
+ break;
674
+ }
675
+ }
676
+ };
677
+ /**
678
+ * Main Logger class providing structured logging capabilities
679
+ */
680
+ var Logger = class {
681
+ constructor(config = {}) {
682
+ this.config = {
683
+ level: getConfiguredLogLevel(),
684
+ includeTimestamp: true,
685
+ includeContext: true,
686
+ enableConsole: true,
687
+ handlers: [],
688
+ ...config
689
+ };
690
+ this.handlers = [...this.config.handlers || []];
691
+ if (this.config.enableConsole) this.handlers.push(new ConsoleLogHandler(this.config));
692
+ }
693
+ /**
694
+ * Add a custom log handler
695
+ */
696
+ addHandler(handler) {
697
+ this.handlers.push(handler);
698
+ }
699
+ /**
700
+ * Remove a log handler
701
+ */
702
+ removeHandler(handler) {
703
+ const index = this.handlers.indexOf(handler);
704
+ if (index > -1) this.handlers.splice(index, 1);
705
+ }
706
+ /**
707
+ * Update logger configuration
708
+ */
709
+ configure(config) {
710
+ this.config = {
711
+ ...this.config,
712
+ ...config
713
+ };
714
+ }
715
+ /**
716
+ * Check if a log level should be output based on current configuration
717
+ */
718
+ shouldLog(level) {
719
+ return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];
720
+ }
721
+ /**
722
+ * Internal logging method that creates log entries and passes them to handlers
723
+ */
724
+ log(level, message, context, metadata) {
725
+ if (!this.shouldLog(level)) return;
726
+ const entry = {
727
+ level,
728
+ message,
729
+ timestamp: /* @__PURE__ */ new Date(),
730
+ context,
731
+ metadata
732
+ };
733
+ this.handlers.forEach((handler) => {
734
+ try {
735
+ handler.handle(entry);
736
+ } catch (error) {
737
+ console.error("Error in log handler:", error);
738
+ }
739
+ });
740
+ }
741
+ /**
742
+ * Log a debug message
743
+ * Used for detailed diagnostic information, typically of interest only when diagnosing problems
744
+ */
745
+ debug(message, context, metadata) {
746
+ this.log("debug", message, context, metadata);
747
+ }
748
+ /**
749
+ * Log an info message
750
+ * Used for general information about application operation
751
+ */
752
+ info(message, context, metadata) {
753
+ this.log("info", message, context, metadata);
754
+ }
755
+ /**
756
+ * Log a warning message
757
+ * Used for potentially problematic situations that don't prevent operation
758
+ */
759
+ warn(message, context, metadata) {
760
+ this.log("warn", message, context, metadata);
761
+ }
762
+ /**
763
+ * Log an error message
764
+ * Used for error events that might still allow the application to continue
765
+ */
766
+ error(message, context, metadata) {
767
+ this.log("error", message, context, metadata);
768
+ }
769
+ /**
770
+ * Create a child logger with a specific context
771
+ */
772
+ child(context) {
773
+ return new ContextLogger(this, context);
774
+ }
775
+ /**
776
+ * Get current logger configuration
777
+ */
778
+ getConfig() {
779
+ return { ...this.config };
780
+ }
781
+ };
782
+ /**
783
+ * Context logger that automatically includes context information
784
+ */
785
+ var ContextLogger = class ContextLogger {
786
+ constructor(logger, context) {
787
+ this.logger = logger;
788
+ this.context = context;
789
+ }
790
+ debug(message, metadata) {
791
+ this.logger.debug(message, this.context, metadata);
792
+ }
793
+ info(message, metadata) {
794
+ this.logger.info(message, this.context, metadata);
795
+ }
796
+ warn(message, metadata) {
797
+ this.logger.warn(message, this.context, metadata);
798
+ }
799
+ error(message, metadata) {
800
+ this.logger.error(message, this.context, metadata);
801
+ }
802
+ child(childContext) {
803
+ return new ContextLogger(this.logger, `${this.context}:${childContext}`);
804
+ }
805
+ };
806
+ const defaultLogger = new Logger({
807
+ level: getConfiguredLogLevel(),
808
+ includeTimestamp: true,
809
+ includeContext: true,
810
+ prefix: "GT"
811
+ });
812
+ const fetchLogger = defaultLogger.child("fetch");
813
+ defaultLogger.child("validation");
814
+ defaultLogger.child("formatting");
815
+ defaultLogger.child("locale");
816
+ const gtInstanceLogger = defaultLogger.child("GT instance");
817
+ //#endregion
818
+ //#region src/formatting/format.ts
819
+ /**
820
+ * Formats a string value with cutoff behavior according to the specified locales and options.
821
+ *
822
+ * @param {Object} params - The parameters for the cutoff formatting.
823
+ * @param {string} params.value - The string value to format with cutoff behavior.
824
+ * @param {string | string[]} [params.locales='en'] - The locales to use for formatting.
825
+ * @param {CutoffFormatOptions} [params.options={}] - Additional options for cutoff formatting.
826
+ * @param {number} [params.options.maxChars] - The maximum number of characters to display.
827
+ * @param {CutoffFormatStyle} [params.options.style='ellipsis'] - The style of the terminator.
828
+ * @param {string} [params.options.terminator] - Optional override for the terminator to use.
829
+ * @param {string} [params.options.separator] - Optional override for the separator between terminator and value.
830
+ *
831
+ * @returns {string} The formatted string with terminator applied if cutoff occurs.
832
+ * @internal
833
+ *
834
+ * @example
835
+ * _formatCutoff({ value: 'Hello, world!', options: { maxChars: 8 } }); // Returns 'Hello, w...'
836
+ *
837
+ * Will fallback to an empty string if formatting fails.
838
+ */
839
+ function _formatCutoff({ value, locales = "en", options = {} }) {
840
+ return intlCache.get("CutoffFormat", locales, options).format(value);
841
+ }
842
+ /**
843
+ * Formats a message according to the specified locales and options.
844
+ *
845
+ * @param {string} message - The message to format.
846
+ * @param {string | string[]} [locales='en'] - The locales to use for formatting.
847
+ * @param {Record<string, any>} [variables={}] - The variables to use for formatting.
848
+ * @returns {string} The formatted message.
849
+ * @internal
850
+ *
851
+ * Will fallback to an empty string
852
+ * TODO: add this to custom formats
853
+ */
854
+ function _formatMessageICU(message, locales = "en", variables = {}) {
855
+ return new IntlMessageFormat(message, locales).format(variables)?.toString() ?? "";
856
+ }
857
+ /**
858
+ * Returns the message as-is without any formatting.
859
+ *
860
+ * @param {string} message - The message to return.
861
+ * @returns {string} The original message, unchanged.
862
+ * @internal
863
+ *
864
+ * TODO: add this to custom formats
865
+ */
866
+ function _formatMessageString(message) {
867
+ return message;
868
+ }
869
+ /**
870
+ * Formats a number according to the specified locales and options.
871
+ *
872
+ * @param {Object} params - The parameters for the number formatting.
873
+ * @param {number} params.value - The number to format.
874
+ * @param {string | string[]} [params.locales=['en']] - The locales to use for formatting.
875
+ * @param {Intl.NumberFormatOptions} [params.options={}] - Additional options for number formatting.
876
+ *
877
+ * @returns {string} The formatted number.
878
+ * @internal
879
+ */
880
+ function _formatNum({ value, locales = ["en"], options = {} }) {
881
+ return intlCache.get("NumberFormat", locales, {
882
+ numberingSystem: "latn",
883
+ ...options
884
+ }).format(value);
885
+ }
886
+ /**
887
+ * Formats a date according to the specified locales and options.
888
+ *
889
+ * @param {Object} params - The parameters for the date formatting.
890
+ * @param {Date} params.value - The date to format.
891
+ * @param {string | string[]} [params.locales='en'] - The locales to use for formatting.
892
+ * @param {Intl.DateTimeFormatOptions} [params.options={}] - Additional options for date formatting.
893
+ *
894
+ * @returns {string} The formatted date.
895
+ * @internal
896
+ */
897
+ function _formatDateTime({ value, locales = ["en"], options = {} }) {
898
+ return intlCache.get("DateTimeFormat", locales, {
899
+ calendar: "gregory",
900
+ numberingSystem: "latn",
901
+ ...options
902
+ }).format(value);
903
+ }
904
+ /**
905
+ * Formats a currency value according to the specified locales, currency, and options.
906
+ *
907
+ * @param {Object} params - The parameters for the currency formatting.
908
+ * @param {number} params.value - The currency value to format.
909
+ * @param {string} params.currency - The currency code (e.g., 'USD').
910
+ * @param {string | string[]} [params.locales=['en']] - The locales to use for formatting.
911
+ * @param {Intl.NumberFormatOptions} [params.options={}] - Additional options for currency formatting.
912
+ *
913
+ * @returns {string} The formatted currency value.
914
+ * @internal
915
+ */
916
+ function _formatCurrency({ value, locales = ["en"], currency = "USD", options = {} }) {
917
+ return intlCache.get("NumberFormat", locales, {
918
+ style: "currency",
919
+ currency,
920
+ numberingSystem: "latn",
921
+ ...options
922
+ }).format(value);
923
+ }
924
+ /**
925
+ * Formats a list of items according to the specified locales and options.
926
+ *
927
+ * @param {Object} params - The parameters for the list formatting.
928
+ * @param {Array<string | number>} params.value - The list of items to format.
929
+ * @param {string | string[]} [params.locales=['en']] - The locales to use for formatting.
930
+ * @param {Intl.ListFormatOptions} [params.options={}] - Additional options for list formatting.
931
+ *
932
+ * @returns {string} The formatted list.
933
+ * @internal
934
+ */
935
+ function _formatList({ value, locales = ["en"], options = {} }) {
936
+ return intlCache.get("ListFormat", locales, {
937
+ type: "conjunction",
938
+ style: "long",
939
+ ...options
940
+ }).format(value);
941
+ }
942
+ /**
943
+ * Formats a list of items according to the specified locales and options.
944
+ * @param {Object} params - The parameters for the list formatting.
945
+ * @param {Array<T>} params.value - The list of items to format.
946
+ * @param {string | string[]} [params.locales=['en']] - The locales to use for formatting.
947
+ * @param {Intl.ListFormatOptions} [params.options={}] - Additional options for list formatting.
948
+ * @returns {Array<T | string>} The formatted list parts.
949
+ * @internal
950
+ */
951
+ function _formatListToParts({ value, locales = ["en"], options = {} }) {
952
+ const formatListParts = intlCache.get("ListFormat", locales, {
953
+ type: "conjunction",
954
+ style: "long",
955
+ ...options
956
+ }).formatToParts(value.map(() => "1"));
957
+ let partIndex = 0;
958
+ return formatListParts.map((part) => {
959
+ if (part.type === "element") return value[partIndex++];
960
+ return part.value;
961
+ });
962
+ }
963
+ /**
964
+ * Selects the best unit and computes the value for relative time formatting
965
+ * based on the difference between a date and a base date.
966
+ * @param {Date} date - The target date.
967
+ * @param {Date} baseDate - The base date to compute relative time from. Must be provided by the caller for hydration safety.
968
+ * @returns {{ value: number, unit: Intl.RelativeTimeFormatUnit }} The computed value and unit.
969
+ * @internal
970
+ */
971
+ function _selectRelativeTimeUnit(date, baseDate) {
972
+ const now = baseDate.getTime();
973
+ const diffMs = date.getTime() - now;
974
+ const absDiffMs = Math.abs(diffMs);
975
+ const sign = diffMs < 0 ? -1 : 1;
976
+ const seconds = Math.floor(absDiffMs / 1e3);
977
+ const minutes = Math.floor(absDiffMs / (1e3 * 60));
978
+ const hours = Math.floor(absDiffMs / (1e3 * 60 * 60));
979
+ const days = Math.floor(absDiffMs / (1e3 * 60 * 60 * 24));
980
+ const weeks = Math.floor(absDiffMs / (1e3 * 60 * 60 * 24 * 7));
981
+ const months = Math.floor(absDiffMs / (1e3 * 60 * 60 * 24 * 30));
982
+ const years = Math.floor(absDiffMs / (1e3 * 60 * 60 * 24 * 365));
983
+ if (seconds < 60) return {
984
+ value: sign * seconds,
985
+ unit: "second"
986
+ };
987
+ if (minutes < 60) return {
988
+ value: sign * minutes,
989
+ unit: "minute"
990
+ };
991
+ if (hours < 24) return {
992
+ value: sign * hours,
993
+ unit: "hour"
994
+ };
995
+ if (days < 7) return {
996
+ value: sign * days,
997
+ unit: "day"
998
+ };
999
+ if (days < 28) return {
1000
+ value: sign * weeks,
1001
+ unit: "week"
1002
+ };
1003
+ if (months < 1) return {
1004
+ value: sign * weeks,
1005
+ unit: "week"
1006
+ };
1007
+ if (months < 12) return {
1008
+ value: sign * months,
1009
+ unit: "month"
1010
+ };
1011
+ if (years < 1) return {
1012
+ value: sign * months,
1013
+ unit: "month"
1014
+ };
1015
+ return {
1016
+ value: sign * years,
1017
+ unit: "year"
1018
+ };
1019
+ }
1020
+ /**
1021
+ * Formats a relative time from a Date, automatically selecting the best unit.
1022
+ * @internal
1023
+ */
1024
+ function _formatRelativeTimeFromDate({ date, baseDate, locales = ["en"], options = {} }) {
1025
+ const { value, unit } = _selectRelativeTimeUnit(date, baseDate);
1026
+ return _formatRelativeTime({
1027
+ value,
1028
+ unit,
1029
+ locales,
1030
+ options
1031
+ });
1032
+ }
1033
+ /**
1034
+ * Formats a relative time value according to the specified locales and options.
1035
+ *
1036
+ * @param {Object} params - The parameters for the relative time formatting.
1037
+ * @param {number} params.value - The relative time value to format.
1038
+ * @param {Intl.RelativeTimeFormatUnit} params.unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year').
1039
+ * @param {string | string[]} [params.locales=['en']] - The locales to use for formatting.
1040
+ * @param {Intl.RelativeTimeFormatOptions} [params.options={}] - Additional options for relative time formatting.
1041
+ *
1042
+ * @returns {string} The formatted relative time string.
1043
+ * @internal
1044
+ */
1045
+ function _formatRelativeTime({ value, unit, locales = ["en"], options = {} }) {
1046
+ return intlCache.get("RelativeTimeFormat", locales, {
1047
+ style: "long",
1048
+ numeric: "auto",
1049
+ ...options
1050
+ }).format(value, unit);
1051
+ }
1052
+ //#endregion
1053
+ //#region src/locales/getLocaleName.ts
1054
+ /**
1055
+ * Retrieves the display name(s) of locale code(s) using Intl.DisplayNames.
1056
+ *
1057
+ * @param {string} locale - A BCP-47 locale code.
1058
+ * @param {string} [defaultLocale=libraryDefaultLocale] - The locale for display names.
1059
+ * @returns {string} The display name(s) corresponding to the code(s), or empty string(s) if invalid.
1060
+ * @internal
1061
+ */
1062
+ function _getLocaleName(locale, defaultLocale = "en", customMapping) {
1063
+ const aliasedLocale = locale;
1064
+ if (customMapping && shouldUseCanonicalLocale(locale, customMapping)) locale = customMapping[locale].code;
1065
+ defaultLocale ||= "en";
1066
+ try {
1067
+ const standardizedLocale = _standardizeLocale(locale);
1068
+ if (customMapping) for (const l of [
1069
+ aliasedLocale,
1070
+ locale,
1071
+ standardizedLocale,
1072
+ intlCache.get("Locale", standardizedLocale).language
1073
+ ]) {
1074
+ const customName = getCustomProperty(customMapping, l, "name");
1075
+ if (customName) return customName;
1076
+ }
1077
+ return intlCache.get("DisplayNames", [
1078
+ defaultLocale,
1079
+ standardizedLocale,
1080
+ "en"
1081
+ ], { type: "language" }).of(standardizedLocale) || "";
1082
+ } catch {
1083
+ return "";
1084
+ }
1085
+ }
1086
+ //#endregion
1087
+ //#region src/locales/getLocaleDirection.ts
1088
+ /**
1089
+ * Get the text direction for a given locale code using the Intl.Locale API.
1090
+ *
1091
+ * @param {string} code - The locale code to check.
1092
+ * @returns {string} - 'rtl' if the language is right-to-left, otherwise 'ltr'.
1093
+ * @internal
1094
+ */
1095
+ function _getLocaleDirection(code) {
1096
+ try {
1097
+ const textInfoDirection = extractDirectionWithTextInfo(intlCache.get("Locale", code));
1098
+ if (textInfoDirection) return textInfoDirection;
1099
+ } catch {}
1100
+ const { scriptCode, languageCode } = _getLocaleProperties(code);
1101
+ if (scriptCode) return isRtlScript(scriptCode) ? "rtl" : "ltr";
1102
+ if (languageCode) return isRtlLanguage(languageCode) ? "rtl" : "ltr";
1103
+ return "ltr";
1104
+ }
1105
+ const RTL_SCRIPTS = new Set([
1106
+ "arab",
1107
+ "adlm",
1108
+ "hebr",
1109
+ "nkoo",
1110
+ "rohg",
1111
+ "samr",
1112
+ "syrc",
1113
+ "thaa",
1114
+ "yezi"
1115
+ ]);
1116
+ const RTL_LANGUAGES = new Set([
1117
+ "ar",
1118
+ "arc",
1119
+ "ckb",
1120
+ "dv",
1121
+ "fa",
1122
+ "he",
1123
+ "iw",
1124
+ "ku",
1125
+ "lrc",
1126
+ "nqo",
1127
+ "ps",
1128
+ "pnb",
1129
+ "sd",
1130
+ "syr",
1131
+ "ug",
1132
+ "ur",
1133
+ "yi"
1134
+ ]);
1135
+ /**
1136
+ * Handles extracting direction via textInfo property
1137
+ * @param Locale - Intl.Locale object
1138
+ * @returns {'ltr' | 'rtl'} - The direction of the locale
1139
+ *
1140
+ * Intl.Locale.prototype.getTextInfo() / textInfo property incorporated in ES2024 Specification.
1141
+ * This is not supported by all browsers yet.
1142
+ * See: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTextInfo#browser_compatibility}
1143
+ */
1144
+ function extractDirectionWithTextInfo(locale) {
1145
+ if ("textInfo" in locale && typeof locale.textInfo === "object" && locale.textInfo !== null && "direction" in locale.textInfo && (locale.textInfo?.direction === "rtl" || locale.textInfo?.direction === "ltr")) return locale.textInfo?.direction;
1146
+ }
1147
+ function isRtlScript(script) {
1148
+ return script ? RTL_SCRIPTS.has(script.toLowerCase()) : false;
1149
+ }
1150
+ function isRtlLanguage(language) {
1151
+ return language ? RTL_LANGUAGES.has(language.toLowerCase()) : false;
1152
+ }
1153
+ //#endregion
1154
+ //#region src/locales/isSupersetLocale.ts
1155
+ /**
1156
+ * @internal
1157
+ */
1158
+ function _isSupersetLocale(superLocale, subLocale) {
1159
+ try {
1160
+ const { language: languageSuper, region: regionSuper, script: scriptSuper } = intlCache.get("Locale", _standardizeLocale(superLocale));
1161
+ const { language: languageSub, region: regionSub, script: scriptSub } = intlCache.get("Locale", _standardizeLocale(subLocale));
1162
+ if (languageSuper !== languageSub) return false;
1163
+ if (regionSuper && regionSuper !== regionSub) return false;
1164
+ if (scriptSuper && scriptSuper !== scriptSub) return false;
1165
+ return true;
1166
+ } catch (error) {
1167
+ console.error(error);
1168
+ return false;
1169
+ }
1170
+ }
1171
+ //#endregion
1172
+ //#region src/logging/errors.ts
1173
+ const GT_ERROR_PREFIX = "GT Error:";
1174
+ const translationTimeoutError = (timeout) => `${GT_ERROR_PREFIX} Translation request timed out after ${timeout}ms.`;
1175
+ const translationRequestFailedError = (error) => `${GT_ERROR_PREFIX} Translation request failed. Error: ${error}`;
1176
+ const apiError = (status, statusText, error) => `${GT_ERROR_PREFIX} API returned error status. Status: ${status}, Status Text: ${statusText}, Error: ${error}`;
1177
+ `${GT_ERROR_PREFIX}`;
1178
+ const noTargetLocaleProvidedError = (functionName) => `${GT_ERROR_PREFIX} Cannot call \`${functionName}\` without a specified locale. Either pass a locale to the \`${functionName}\` function or specify a targetLocale in the GT constructor.`;
1179
+ const noSourceLocaleProvidedError = (functionName) => `${GT_ERROR_PREFIX} Cannot call \`${functionName}\` without a specified locale. Either pass a locale to the \`${functionName}\` function or specify a sourceLocale in the GT constructor.`;
1180
+ const noProjectIdProvidedError = (functionName) => `${GT_ERROR_PREFIX} Cannot call \`${functionName}\` without a specified project ID. Either pass a project ID to the \`${functionName}\` function or specify a projectId in the GT constructor.`;
1181
+ const noApiKeyProvidedError = (functionName) => `${GT_ERROR_PREFIX} Cannot call \`${functionName}\` without a specified API key. Either pass an API key to the \`${functionName}\` function or specify an apiKey in the GT constructor.`;
1182
+ const invalidLocaleError = (locale) => `${GT_ERROR_PREFIX} Invalid locale: ${locale}.`;
1183
+ const invalidLocalesError = (locales) => `${GT_ERROR_PREFIX} Invalid locales: ${locales.join(", ")}.`;
1184
+ //#endregion
1185
+ //#region src/translate/utils/fetchWithTimeout.ts
1186
+ /**
1187
+ * @internal
1188
+ *
1189
+ * Wraps the fetch function with a timeout.
1190
+ *
1191
+ * @param url - The URL to fetch.
1192
+ * @param options - The options to pass to the fetch function.
1193
+ * @param timeout - The timeout in milliseconds.
1194
+ * @returns The response from the fetch function.
1195
+ */
1196
+ async function fetchWithTimeout(url, options, timeout) {
1197
+ const controller = new AbortController();
1198
+ const signal = controller.signal;
1199
+ timeout = timeout ? timeout : defaultTimeout;
1200
+ const timeoutId = timeout ? setTimeout(() => controller.abort(), timeout) : null;
1201
+ try {
1202
+ return await fetch(url, {
1203
+ ...options,
1204
+ signal
1205
+ });
1206
+ } catch (error) {
1207
+ if (error instanceof Error && error.name === "AbortError") throw translationTimeoutError(timeout);
1208
+ throw error;
1209
+ } finally {
1210
+ if (timeoutId) clearTimeout(timeoutId);
1211
+ }
1212
+ }
1213
+ //#endregion
1214
+ //#region src/translate/utils/validateResponse.ts
1215
+ async function validateResponse(response) {
1216
+ if (!response.ok) {
1217
+ let errorMsg = "Unknown error";
1218
+ try {
1219
+ const text = await response.text();
1220
+ try {
1221
+ errorMsg = JSON.parse(text).error;
1222
+ } catch {
1223
+ errorMsg = text || "Unknown error";
1224
+ }
1225
+ } catch {}
1226
+ throw new ApiError(apiError(response.status, response.statusText, errorMsg), response.status, errorMsg);
1227
+ }
1228
+ }
1229
+ //#endregion
1230
+ //#region src/translate/utils/handleFetchError.ts
1231
+ function handleFetchError(error, timeout) {
1232
+ if (error instanceof Error && error.name === "AbortError") {
1233
+ const errorMessage = translationTimeoutError(timeout);
1234
+ fetchLogger.error(errorMessage);
1235
+ throw new Error(errorMessage);
1236
+ }
1237
+ const errorMessage = translationRequestFailedError(error instanceof Error ? error.message : String(error));
1238
+ fetchLogger.error(errorMessage);
1239
+ throw error;
1240
+ }
1241
+ //#endregion
1242
+ //#region src/translate/api.ts
1243
+ const API_VERSION$1 = "2026-03-06.v1";
1244
+ //#endregion
1245
+ //#region src/translate/utils/generateRequestHeaders.ts
1246
+ function generateRequestHeaders(config, excludeContentType = false) {
1247
+ const authHeaders = {
1248
+ ...!excludeContentType && { "Content-Type": "application/json" },
1249
+ "x-gt-project-id": config.projectId
1250
+ };
1251
+ if (config.apiKey) if (config.apiKey.startsWith("gtx-internal-")) authHeaders["x-gt-internal-api-key"] = config.apiKey;
1252
+ else authHeaders["x-gt-api-key"] = config.apiKey;
1253
+ authHeaders["gt-api-version"] = API_VERSION$1;
1254
+ return authHeaders;
1255
+ }
1256
+ //#endregion
1257
+ //#region src/translate/utils/apiRequest.ts
1258
+ const MAX_RETRIES = 3;
1259
+ const INITIAL_DELAY_MS = 500;
1260
+ function sleep(ms) {
1261
+ return new Promise((resolve) => setTimeout(resolve, ms));
1262
+ }
1263
+ function getRetryDelay(policy, attempt) {
1264
+ switch (policy) {
1265
+ case "linear": return INITIAL_DELAY_MS * (attempt + 1);
1266
+ case "exponential": return INITIAL_DELAY_MS * 2 ** attempt;
1267
+ default: return 0;
1268
+ }
1269
+ }
1270
+ /**
1271
+ * @internal
1272
+ *
1273
+ * Makes an API request with automatic retry for 5XX errors.
1274
+ *
1275
+ * Encapsulates URL construction, fetch with timeout, error handling,
1276
+ * response validation, and JSON parsing.
1277
+ *
1278
+ * @param config - The configuration for the API call
1279
+ * @param endpoint - The API endpoint path (e.g. '/v2/project/jobs/info')
1280
+ * @param options - Optional request options
1281
+ * @returns The parsed JSON response
1282
+ */
1283
+ async function apiRequest(config, endpoint, options) {
1284
+ const timeout = options?.timeout ?? 6e4;
1285
+ const url = `${config.baseUrl || "https://api2.gtx.dev"}${endpoint}`;
1286
+ const method = options?.method ?? "POST";
1287
+ const retryPolicy = options?.retryPolicy ?? "exponential";
1288
+ const maxRetries = retryPolicy === "none" ? 0 : MAX_RETRIES;
1289
+ const requestInit = {
1290
+ method,
1291
+ headers: generateRequestHeaders(config)
1292
+ };
1293
+ if (options?.body !== void 0) requestInit.body = JSON.stringify(options.body);
1294
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
1295
+ let response;
1296
+ try {
1297
+ response = await fetchWithTimeout(url, requestInit, timeout);
1298
+ } catch (error) {
1299
+ if (attempt < maxRetries) {
1300
+ await sleep(getRetryDelay(retryPolicy, attempt));
1301
+ continue;
1302
+ }
1303
+ handleFetchError(error, timeout);
1304
+ }
1305
+ if (response.status >= 500 && attempt < maxRetries) {
1306
+ await sleep(getRetryDelay(retryPolicy, attempt));
1307
+ continue;
1308
+ }
1309
+ await validateResponse(response);
1310
+ return await response.json();
1311
+ }
1312
+ throw new Error("Max retries exceeded");
1313
+ }
1314
+ //#endregion
1315
+ //#region src/translate/translateMany.ts
1316
+ async function _translateMany(requests, globalMetadata, config, timeout) {
1317
+ const isArray = Array.isArray(requests);
1318
+ const hashOrder = isArray ? [] : void 0;
1319
+ const requestsObject = {};
1320
+ const entries = isArray ? requests.map((r) => [void 0, r]) : Object.entries(requests);
1321
+ for (const [key, request] of entries) {
1322
+ const { source, metadata } = typeof request === "string" ? { source: request } : request;
1323
+ const hash = key ?? metadata?.hash ?? hashSource({
1324
+ source,
1325
+ dataFormat: metadata?.dataFormat ?? "STRING",
1326
+ ...metadata ?? {}
1327
+ });
1328
+ hashOrder?.push(hash);
1329
+ requestsObject[hash] = {
1330
+ source,
1331
+ metadata
1332
+ };
1333
+ }
1334
+ const response = await apiRequest({
1335
+ ...config,
1336
+ baseUrl: config.baseUrl || "https://runtime2.gtx.dev"
1337
+ }, `/v2/translate`, {
1338
+ body: {
1339
+ requests: requestsObject,
1340
+ targetLocale: globalMetadata.targetLocale,
1341
+ sourceLocale: globalMetadata.sourceLocale,
1342
+ metadata: globalMetadata
1343
+ },
1344
+ timeout,
1345
+ retryPolicy: "none"
1346
+ });
1347
+ if (hashOrder) return hashOrder.map((hash) => response[hash] ?? {
1348
+ success: false,
1349
+ error: "No translation returned",
1350
+ code: 500
1351
+ });
1352
+ return response;
1353
+ }
1354
+ //#endregion
1355
+ //#region src/translate/setupProject.ts
1356
+ /**
1357
+ * @internal
1358
+ * Enqueues files for project setup the General Translation API.
1359
+ * @param files - References of files to translate (file content already uploaded)
1360
+ * @param config - The configuration for the API call
1361
+ * @param timeoutMS - The timeout in milliseconds
1362
+ * @returns The result of the API call
1363
+ */
1364
+ async function _setupProject(files, config, options) {
1365
+ return apiRequest(config, "/v2/project/setup/generate", {
1366
+ body: {
1367
+ files: files.map((f) => ({
1368
+ branchId: f.branchId,
1369
+ fileId: f.fileId,
1370
+ versionId: f.versionId
1371
+ })),
1372
+ locales: options?.locales,
1373
+ force: options?.force
1374
+ },
1375
+ timeout: options?.timeoutMs
1376
+ });
1377
+ }
1378
+ //#endregion
1379
+ //#region src/translate/utils/batch.ts
1380
+ /**
1381
+ * Splits an array into batches of a specified size.
1382
+ * @param items - The array to split into batches
1383
+ * @param batchSize - The maximum size of each batch
1384
+ * @returns An array of batches
1385
+ */
1386
+ function createBatches(items, batchSize) {
1387
+ const batches = [];
1388
+ for (let i = 0; i < items.length; i += batchSize) batches.push(items.slice(i, i + batchSize));
1389
+ return batches;
1390
+ }
1391
+ /**
1392
+ * Processes items in batches using a provided processor function.
1393
+ *
1394
+ * @param items - The items to process
1395
+ * @param processor - Async function that processes a single batch and returns items
1396
+ * @param options - Optional configuration for batch processing
1397
+ * @returns Promise that resolves to a BatchList containing all processed items
1398
+ *
1399
+ * @example
1400
+ * ```typescript
1401
+ * const result = await processBatches(
1402
+ * files,
1403
+ * async (batch) => {
1404
+ * const response = await uploadFiles(batch);
1405
+ * return response.uploadedFiles;
1406
+ * },
1407
+ * { batchSize: 100 }
1408
+ * );
1409
+ *
1410
+ * console.log(result.data); // All items
1411
+ * console.log(result.count); // Total count
1412
+ * console.log(result.batchCount); // Number of batches processed
1413
+ * ```
1414
+ */
1415
+ async function processBatches(items, processor, options = {}) {
1416
+ const { batchSize = 100, parallel = true } = options;
1417
+ if (items.length === 0) return {
1418
+ data: [],
1419
+ count: 0,
1420
+ batchCount: 0
1421
+ };
1422
+ const batches = createBatches(items, batchSize);
1423
+ const allItems = [];
1424
+ if (parallel) {
1425
+ const results = await Promise.all(batches.map((batch) => processor(batch)));
1426
+ for (const result of results) if (result) allItems.push(...result);
1427
+ } else for (const batch of batches) {
1428
+ const result = await processor(batch);
1429
+ if (result) allItems.push(...result);
1430
+ }
1431
+ return {
1432
+ data: allItems,
1433
+ count: allItems.length,
1434
+ batchCount: batches.length
1435
+ };
1436
+ }
1437
+ //#endregion
1438
+ //#region src/translate/enqueueFiles.ts
1439
+ /**
1440
+ * @internal
1441
+ * Enqueues files for translation in the General Translation API.
1442
+ * @param files - References of files to translate (file content already uploaded)
1443
+ * @param options - The options for the API call
1444
+ * @param config - The configuration for the API call
1445
+ * @returns The result of the API call
1446
+ */
1447
+ async function _enqueueFiles(files, options, config) {
1448
+ validateFileFormatTransforms(files);
1449
+ const result = await processBatches(files, async (batch) => {
1450
+ const apiResult = await apiRequest(config, "/v2/project/translations/enqueue", {
1451
+ body: {
1452
+ files: batch.map((f) => ({
1453
+ branchId: f.branchId,
1454
+ fileId: f.fileId,
1455
+ versionId: f.versionId,
1456
+ fileName: f.fileName,
1457
+ transformFormat: f.transformFormat
1458
+ })),
1459
+ targetLocales: options.targetLocales,
1460
+ sourceLocale: options.sourceLocale,
1461
+ requireApproval: options.requireApproval,
1462
+ modelProvider: options.modelProvider,
1463
+ force: options.force
1464
+ },
1465
+ timeout: options.timeout
1466
+ });
1467
+ return Array.from(Object.entries(apiResult.jobData));
1468
+ }, { batchSize: 100 });
1469
+ return {
1470
+ jobData: Object.fromEntries(result.data.map(([jobId, jobData]) => [jobId, jobData])),
1471
+ locales: options.targetLocales,
1472
+ message: `Successfully enqueued ${result.count} file translation jobs in ${result.batchCount} batch(es)`
1473
+ };
1474
+ }
1475
+ //#endregion
1476
+ //#region src/translate/createTag.ts
1477
+ /**
1478
+ * @internal
1479
+ * Creates or upserts a file tag in the General Translation API.
1480
+ * @param options - The tag creation options
1481
+ * @param config - The configuration for the API call
1482
+ * @returns The created or updated tag
1483
+ */
1484
+ async function _createTag(options, config) {
1485
+ return await apiRequest(config, "/v2/project/tags/create", { body: {
1486
+ tagId: options.tagId,
1487
+ files: options.files,
1488
+ ...options.message && { message: options.message }
1489
+ } });
1490
+ }
1491
+ //#endregion
1492
+ //#region src/translate/downloadFileBatch.ts
1493
+ /**
1494
+ * @internal
1495
+ * Downloads multiple translation files in batches.
1496
+ * @param files - Array of files to download
1497
+ * @param options - The options for the API call
1498
+ * @param config - The configuration for the request
1499
+ * @returns Promise resolving to a BatchList with all downloaded files
1500
+ */
1501
+ async function _downloadFileBatch(requests, options, config) {
1502
+ return processBatches(requests, async (batch) => {
1503
+ return (await apiRequest(config, "/v2/project/files/download", {
1504
+ body: batch,
1505
+ timeout: options.timeout
1506
+ })).files.map((file) => ({
1507
+ ...file,
1508
+ data: decode(file.data)
1509
+ }));
1510
+ }, { batchSize: 100 });
1511
+ }
1512
+ //#endregion
1513
+ //#region src/translate/submitUserEditDiffs.ts
1514
+ /**
1515
+ * @internal
1516
+ * Submits user edit diffs so the service can learn/persist user-intended rules.
1517
+ */
1518
+ async function _submitUserEditDiffs(payload, config, options = {}) {
1519
+ await processBatches(payload.diffs, async (batch) => {
1520
+ await apiRequest(config, "/v2/project/files/diffs", {
1521
+ body: { diffs: batch },
1522
+ timeout: options.timeout
1523
+ });
1524
+ return [{ success: true }];
1525
+ }, { batchSize: 100 });
1526
+ return { success: true };
1527
+ }
1528
+ //#endregion
1529
+ //#region src/locales/getRegionProperties.ts
1530
+ /**
1531
+ * Retrieves multiple properties for a given region code, including:
1532
+ * - `code`: the original region code
1533
+ * - `name`: the localized display name
1534
+ * - `emoji`: the associated flag or symbol
1535
+ *
1536
+ * Behavior:
1537
+ * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
1538
+ * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
1539
+ * - Otherwise, uses `Intl.DisplayNames` to get the localized region name in the given `defaultLocale`,
1540
+ * falling back to `libraryDefaultLocale`.
1541
+ * - Falls back to the region code as `name` if display name resolution fails.
1542
+ * - Falls back to `defaultEmoji` if no emoji mapping is found in `emojis` or `customMapping`.
1543
+ *
1544
+ * @param {string} region - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
1545
+ * @param {string} [defaultLocale=libraryDefaultLocale] - The locale to use when localizing the region name.
1546
+ * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
1547
+ * @returns {{ code: string, name: string, emoji: string }} An object containing:
1548
+ * - `code`: the input region code
1549
+ * - `name`: the localized or custom region name
1550
+ * - `emoji`: the matching emoji flag or symbol
1551
+ * @internal
1552
+ *
1553
+ * @example
1554
+ * _getRegionProperties('US', 'en');
1555
+ * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
1556
+ *
1557
+ * @example
1558
+ * _getRegionProperties('US', 'fr');
1559
+ * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
1560
+ *
1561
+ * @example
1562
+ * _getRegionProperties('US', 'en', { US: { name: 'USA', emoji: '🗽' } });
1563
+ * // => { code: 'US', name: 'USA', emoji: '🗽' }
1564
+ */
1565
+ function _getRegionProperties(region, defaultLocale = "en", customMapping) {
1566
+ defaultLocale ||= "en";
1567
+ try {
1568
+ return {
1569
+ code: region,
1570
+ name: intlCache.get("DisplayNames", [defaultLocale, "en"], { type: "region" }).of(region) || region,
1571
+ emoji: emojis[region] || "🌍",
1572
+ ...customMapping?.[region]
1573
+ };
1574
+ } catch {
1575
+ return {
1576
+ code: region,
1577
+ name: region,
1578
+ emoji: defaultEmoji,
1579
+ ...customMapping?.[region]
1580
+ };
1581
+ }
1582
+ }
1583
+ //#endregion
1584
+ //#region src/locales/resolveAliasLocale.ts
1585
+ /**
1586
+ * Resolves the alias locale for a given locale.
1587
+ * @param locale - The locale to resolve the alias locale for
1588
+ * @param customMapping - The custom mapping to use for resolving the alias locale
1589
+ * @returns The alias locale
1590
+ */
1591
+ function _resolveAliasLocale(locale, customMapping) {
1592
+ let reverseCustomMapping;
1593
+ if (customMapping) reverseCustomMapping = Object.fromEntries(Object.entries(customMapping).filter(([, value]) => value && typeof value === "object" && "code" in value).map(([key, value]) => [value.code, key]));
1594
+ return reverseCustomMapping?.[locale] || locale;
1595
+ }
1596
+ //#endregion
1597
+ //#region src/locales/resolveCanonicalLocale.ts
1598
+ /**
1599
+ * Resolves the canonical locale for a given locale.
1600
+ * @param locale - The locale to resolve the canonical locale for
1601
+ * @param customMapping - The custom mapping to use for resolving the canonical locale
1602
+ * @returns The canonical locale
1603
+ */
1604
+ function _resolveCanonicalLocale(locale, customMapping) {
1605
+ if (customMapping && shouldUseCanonicalLocale(locale, customMapping)) return customMapping[locale].code;
1606
+ return locale;
1607
+ }
1608
+ //#endregion
1609
+ //#region src/translate/uploadSourceFiles.ts
1610
+ /**
1611
+ * @internal
1612
+ * Uploads source files to the General Translation API in batches.
1613
+ * @param files - The files to upload
1614
+ * @param options - The options for the API call
1615
+ * @param config - The configuration for the API call
1616
+ * @returns Promise resolving to a BatchList with all uploaded files
1617
+ */
1618
+ async function _uploadSourceFiles(files, options, config) {
1619
+ return processBatches(files, async (batch) => {
1620
+ return (await apiRequest(config, "/v2/project/files/upload-files", {
1621
+ body: {
1622
+ data: batch.map(({ source }) => ({ source: {
1623
+ content: encode(source.content),
1624
+ fileName: source.fileName,
1625
+ fileFormat: source.fileFormat,
1626
+ locale: source.locale,
1627
+ dataFormat: source.dataFormat,
1628
+ formatMetadata: source.formatMetadata,
1629
+ fileId: source.fileId,
1630
+ versionId: source.versionId,
1631
+ branchId: source.branchId,
1632
+ incomingBranchId: source.incomingBranchId,
1633
+ checkedOutBranchId: source.checkedOutBranchId
1634
+ } })),
1635
+ sourceLocale: options.sourceLocale
1636
+ },
1637
+ timeout: options.timeout
1638
+ })).uploadedFiles || [];
1639
+ }, { batchSize: 100 });
1640
+ }
1641
+ //#endregion
1642
+ //#region src/translate/uploadTranslations.ts
1643
+ /**
1644
+ * @internal
1645
+ * Uploads multiple translations to the General Translation API in batches.
1646
+ * @param files - Translations to upload with their source
1647
+ * @param options - The options for the API call
1648
+ * @param config - The configuration for the API call
1649
+ * @returns Promise resolving to a BatchList with all uploaded files
1650
+ */
1651
+ async function _uploadTranslations(files, options, config) {
1652
+ validateFileFormatTransforms(files.map(({ source }) => source));
1653
+ return processBatches(files, async (batch) => {
1654
+ return (await apiRequest(config, "/v2/project/files/upload-translations", {
1655
+ body: {
1656
+ data: batch.map(({ source, translations }) => ({
1657
+ source: {
1658
+ content: encode(source.content),
1659
+ fileName: source.fileName,
1660
+ fileFormat: source.fileFormat,
1661
+ transformFormat: source.transformFormat,
1662
+ locale: source.locale,
1663
+ dataFormat: source.dataFormat,
1664
+ formatMetadata: source.formatMetadata,
1665
+ fileId: source.fileId,
1666
+ versionId: source.versionId,
1667
+ branchId: source.branchId
1668
+ },
1669
+ translations: translations.map((t) => ({
1670
+ content: encode(t.content),
1671
+ fileName: t.fileName,
1672
+ fileFormat: t.fileFormat,
1673
+ locale: t.locale,
1674
+ dataFormat: t.dataFormat,
1675
+ fileId: t.fileId,
1676
+ versionId: t.versionId,
1677
+ branchId: t.branchId
1678
+ }))
1679
+ })),
1680
+ sourceLocale: options.sourceLocale
1681
+ },
1682
+ timeout: options.timeout
1683
+ })).uploadedFiles || [];
1684
+ }, { batchSize: 100 });
1685
+ }
1686
+ //#endregion
1687
+ //#region src/translate/querySourceFile.ts
1688
+ /**
1689
+ * @internal
1690
+ * Gets the source file and translation information for a given file ID and version ID.
1691
+ * @param query - The file ID and version ID to get the source file and translation information for
1692
+ * @param options - The options for the API call
1693
+ * @param config - The configuration for the request
1694
+ * @returns The source file and translation information for the given file ID and version ID
1695
+ */
1696
+ async function _querySourceFile(query, options, config) {
1697
+ const branchId = query.branchId;
1698
+ const versionId = query.versionId;
1699
+ const fileId = query.fileId;
1700
+ const searchParams = new URLSearchParams();
1701
+ if (branchId) searchParams.set("branchId", branchId);
1702
+ if (versionId) searchParams.set("versionId", versionId);
1703
+ return apiRequest(config, `/v2/project/translations/files/status/${encodeURIComponent(fileId)}?${searchParams.toString()}`, {
1704
+ method: "GET",
1705
+ timeout: options.timeout
1706
+ });
1707
+ }
1708
+ //#endregion
1709
+ //#region src/projects/getProjectData.ts
1710
+ /**
1711
+ * @internal
1712
+ * Gets the project data for a given project ID.
1713
+ * @param projectId - The project ID to get the project data for
1714
+ * @param options - The options for the API call
1715
+ * @param config - The configuration for the request
1716
+ * @returns The project data for the given project ID
1717
+ */
1718
+ async function _getProjectData(projectId, options, config) {
1719
+ const { baseUrl } = config;
1720
+ const timeout = options.timeout ? options.timeout : defaultTimeout;
1721
+ const url = `${baseUrl || "https://api2.gtx.dev"}/v2/project/info/${encodeURIComponent(projectId)}`;
1722
+ let response;
1723
+ try {
1724
+ response = await fetchWithTimeout(url, {
1725
+ method: "GET",
1726
+ headers: generateRequestHeaders(config)
1727
+ }, timeout);
1728
+ } catch (error) {
1729
+ handleFetchError(error, timeout);
1730
+ }
1731
+ await validateResponse(response);
1732
+ return await response.json();
1733
+ }
1734
+ //#endregion
1735
+ //#region src/translate/checkJobStatus.ts
1736
+ /**
1737
+ * @internal
1738
+ * Queries job statuses for a project
1739
+ * @param jobIds - Job IDs
1740
+ * @param config - The configuration for the API call
1741
+ * @param timeoutMS - The timeout in milliseconds
1742
+ * @returns The result of the API call
1743
+ */
1744
+ async function _checkJobStatus(jobIds, config, timeoutMs) {
1745
+ return apiRequest(config, "/v2/project/jobs/info", {
1746
+ body: { jobIds },
1747
+ timeout: timeoutMs
1748
+ });
1749
+ }
1750
+ //#endregion
1751
+ //#region src/translate/awaitJobs.ts
1752
+ /**
1753
+ * @internal
1754
+ * Polls job statuses until all jobs are finished or the timeout is reached.
1755
+ * @param enqueueResult - The result from enqueueFiles
1756
+ * @param options - Polling configuration
1757
+ * @param config - API credentials and configuration
1758
+ * @returns The final status of all jobs
1759
+ */
1760
+ async function _awaitJobs(enqueueResult, options, config) {
1761
+ const pollingInterval = (options?.pollingIntervalSeconds ?? 5) * 1e3;
1762
+ const timeout = options?.timeoutSeconds !== void 0 ? options.timeoutSeconds * 1e3 : 600 * 1e3;
1763
+ const jobIds = Object.keys(enqueueResult.jobData);
1764
+ if (jobIds.length === 0) return {
1765
+ complete: true,
1766
+ jobs: []
1767
+ };
1768
+ const startTime = Date.now();
1769
+ const finalStatuses = new Map(jobIds.map((id) => [id, {
1770
+ jobId: id,
1771
+ status: "unknown"
1772
+ }]));
1773
+ const pendingJobIds = new Set(jobIds);
1774
+ while (pendingJobIds.size > 0) {
1775
+ const statuses = await _checkJobStatus(Array.from(pendingJobIds), config);
1776
+ for (const job of statuses) if (job.status === "completed" || job.status === "failed" || job.status === "unknown") {
1777
+ finalStatuses.set(job.jobId, {
1778
+ jobId: job.jobId,
1779
+ status: job.status,
1780
+ ...job.error ? { error: job.error } : {}
1781
+ });
1782
+ pendingJobIds.delete(job.jobId);
1783
+ } else finalStatuses.set(job.jobId, {
1784
+ jobId: job.jobId,
1785
+ status: job.status
1786
+ });
1787
+ if (pendingJobIds.size === 0) break;
1788
+ if (Date.now() - startTime >= timeout) break;
1789
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
1790
+ }
1791
+ return {
1792
+ complete: pendingJobIds.size === 0,
1793
+ jobs: Array.from(finalStatuses.values())
1794
+ };
1795
+ }
1796
+ //#endregion
1797
+ //#region src/translate/queryFileData.ts
1798
+ /**
1799
+ * @internal
1800
+ * Queries data about one or more source or translation files.
1801
+ * @param data - Object mapping source or translation file information
1802
+ * @param options - The options for the API call
1803
+ * @param config - The configuration for the API call
1804
+ * @returns The file data
1805
+ */
1806
+ async function _queryFileData(data, options = {}, config) {
1807
+ return apiRequest(config, "/v2/project/files/info", {
1808
+ body: {
1809
+ sourceFiles: data.sourceFiles?.map((item) => ({
1810
+ fileId: item.fileId,
1811
+ versionId: item.versionId,
1812
+ branchId: item.branchId
1813
+ })),
1814
+ translatedFiles: data.translatedFiles?.map((item) => ({
1815
+ fileId: item.fileId,
1816
+ versionId: item.versionId,
1817
+ branchId: item.branchId,
1818
+ locale: item.locale
1819
+ }))
1820
+ },
1821
+ timeout: options.timeout
1822
+ });
1823
+ }
1824
+ //#endregion
1825
+ //#region src/translate/queryBranchData.ts
1826
+ /**
1827
+ * @internal
1828
+ * Queries branch information from the API.
1829
+ * @param query - Object mapping the current branch and incoming branches
1830
+ * @param config - The configuration for the API call
1831
+ * @returns The branch information
1832
+ */
1833
+ async function _queryBranchData(query, config) {
1834
+ return apiRequest(config, "/v2/project/branches/info", { body: query });
1835
+ }
1836
+ //#endregion
1837
+ //#region src/translate/createBranch.ts
1838
+ /**
1839
+ * @internal
1840
+ * Creates a new branch in the API.
1841
+ * @param query - Object mapping the branch name and default branch flag
1842
+ * @param config - The configuration for the API call
1843
+ * @returns The created branch information
1844
+ */
1845
+ async function _createBranch(query, config) {
1846
+ return apiRequest(config, "/v2/project/branches/create", { body: query });
1847
+ }
1848
+ //#endregion
1849
+ //#region src/translate/processFileMoves.ts
1850
+ /**
1851
+ * @internal
1852
+ * Processes file moves by cloning source files and translations with new fileIds.
1853
+ * Called when the CLI detects that files have been moved/renamed.
1854
+ * @param moves - Array of move mappings (old fileId to new fileId)
1855
+ * @param options - Options including branchId and timeout
1856
+ * @param config - The configuration for the API call
1857
+ * @returns Promise resolving to the move results
1858
+ */
1859
+ async function _processFileMoves(moves, options, config) {
1860
+ if (moves.length === 0) return {
1861
+ results: [],
1862
+ summary: {
1863
+ total: 0,
1864
+ succeeded: 0,
1865
+ failed: 0
1866
+ }
1867
+ };
1868
+ const batchResult = await processBatches(moves, async (batch) => {
1869
+ return (await apiRequest(config, "/v2/project/files/moves", {
1870
+ body: {
1871
+ branchId: options.branchId,
1872
+ moves: batch
1873
+ },
1874
+ timeout: options.timeout
1875
+ })).results;
1876
+ }, { batchSize: 100 });
1877
+ const succeeded = batchResult.data.filter((r) => r.success).length;
1878
+ const failed = batchResult.data.filter((r) => !r.success).length;
1879
+ return {
1880
+ results: batchResult.data,
1881
+ summary: {
1882
+ total: moves.length,
1883
+ succeeded,
1884
+ failed
1885
+ }
1886
+ };
1887
+ }
1888
+ //#endregion
1889
+ //#region src/translate/getOrphanedFiles.ts
1890
+ /**
1891
+ * @internal
1892
+ * Gets orphaned files for a branch - files that exist on the branch
1893
+ * but whose fileIds are not in the provided list.
1894
+ * Used for move detection.
1895
+ * @param branchId - The branch to check for orphaned files
1896
+ * @param fileIds - List of current file IDs (files that are NOT orphaned)
1897
+ * @param options - The options for the API call
1898
+ * @param config - The configuration for the API call
1899
+ * @returns The orphaned files
1900
+ */
1901
+ async function _getOrphanedFiles(branchId, fileIds, options = {}, config) {
1902
+ const makeRequest = (batchFileIds) => apiRequest(config, "/v2/project/files/orphaned", {
1903
+ body: {
1904
+ branchId,
1905
+ fileIds: batchFileIds
1906
+ },
1907
+ timeout: options.timeout
1908
+ });
1909
+ if (fileIds.length === 0) return makeRequest([]);
1910
+ const batches = createBatches(fileIds, 100);
1911
+ const batchResults = await Promise.all(batches.map((batch) => makeRequest(batch)));
1912
+ if (batchResults.length === 1) return batchResults[0];
1913
+ const orphanedFileMap = /* @__PURE__ */ new Map();
1914
+ for (const orphan of batchResults[0].orphanedFiles) orphanedFileMap.set(orphan.fileId, orphan);
1915
+ for (let i = 1; i < batchResults.length; i++) {
1916
+ const batchOrphanIds = new Set(batchResults[i].orphanedFiles.map((f) => f.fileId));
1917
+ Array.from(orphanedFileMap.keys()).forEach((fileId) => {
1918
+ if (!batchOrphanIds.has(fileId)) orphanedFileMap.delete(fileId);
1919
+ });
1920
+ }
1921
+ return { orphanedFiles: Array.from(orphanedFileMap.values()) };
1922
+ }
1923
+ //#endregion
1924
+ //#region src/translate/publishFiles.ts
1925
+ /**
1926
+ * @internal
1927
+ * Publishes or unpublishes files on the CDN.
1928
+ * @param files - Array of file entries with publish flags
1929
+ * @param config - The configuration for the API call
1930
+ * @returns The result of the API call
1931
+ */
1932
+ async function _publishFiles(files, config) {
1933
+ return await apiRequest(config, "/v2/project/files/publish", { body: { files } });
1934
+ }
1935
+ //#endregion
1936
+ //#region src/LocaleConfig.ts
1937
+ /**
1938
+ * LocaleConfig is a client-safe locale and formatting helper.
1939
+ *
1940
+ * It intentionally does not store project IDs, API keys, runtime URLs, or any
1941
+ * translation credentials. It only stores locale metadata needed to resolve
1942
+ * aliases, choose formatting fallbacks, and format values with Intl.
1943
+ */
1944
+ var LocaleConfig = class {
1945
+ constructor({ defaultLocale = "en", locales = [], customMapping } = {}) {
1946
+ this.defaultLocale = defaultLocale;
1947
+ this.locales = locales;
1948
+ this.customMapping = customMapping;
1949
+ }
1950
+ get translationLocales() {
1951
+ return this.locales.length ? this.locales : void 0;
1952
+ }
1953
+ resolveCanonicalLocaleList(locales) {
1954
+ return locales.map((locale) => this.resolveCanonicalLocale(locale));
1955
+ }
1956
+ resolveCanonicalLocaleArgs(locales) {
1957
+ return locales.map((locale) => Array.isArray(locale) ? this.resolveCanonicalLocaleList(locale) : this.resolveCanonicalLocale(locale));
1958
+ }
1959
+ toLocaleList(locales) {
1960
+ return Array.isArray(locales) ? locales : [locales];
1961
+ }
1962
+ getFormattingLocales(targetLocale, locales) {
1963
+ return (locales !== void 0 ? this.toLocaleList(locales) : [
1964
+ targetLocale,
1965
+ this.defaultLocale,
1966
+ "en"
1967
+ ]).filter((locale) => !!locale).map((locale) => this.resolveCanonicalLocale(locale));
1968
+ }
1969
+ formatNum(value, targetLocale, options = {}) {
1970
+ const { locales, ...intlOptions } = options;
1971
+ return _formatNum({
1972
+ value,
1973
+ locales: this.getFormattingLocales(targetLocale, locales),
1974
+ options: intlOptions
1975
+ });
1976
+ }
1977
+ formatDateTime(value, targetLocale, options = {}) {
1978
+ const { locales, ...intlOptions } = options;
1979
+ return _formatDateTime({
1980
+ value,
1981
+ locales: this.getFormattingLocales(targetLocale, locales),
1982
+ options: intlOptions
1983
+ });
1984
+ }
1985
+ formatCurrency(value, currency, targetLocale, options = {}) {
1986
+ const { locales, ...intlOptions } = options;
1987
+ return _formatCurrency({
1988
+ value,
1989
+ currency,
1990
+ locales: this.getFormattingLocales(targetLocale, locales),
1991
+ options: intlOptions
1992
+ });
1993
+ }
1994
+ formatRelativeTime(value, unit, targetLocale, options = {}) {
1995
+ const { locales, ...intlOptions } = options;
1996
+ return _formatRelativeTime({
1997
+ value,
1998
+ unit,
1999
+ locales: this.getFormattingLocales(targetLocale, locales),
2000
+ options: intlOptions
2001
+ });
2002
+ }
2003
+ formatRelativeTimeFromDate(date, targetLocale, options = {}) {
2004
+ const { locales, baseDate, ...intlOptions } = options;
2005
+ return _formatRelativeTimeFromDate({
2006
+ date,
2007
+ baseDate: baseDate ?? /* @__PURE__ */ new Date(),
2008
+ locales: this.getFormattingLocales(targetLocale, locales),
2009
+ options: intlOptions
2010
+ });
2011
+ }
2012
+ formatCutoff(value, targetLocale, options = {}) {
2013
+ const { locales, ...formatOptions } = options;
2014
+ return _formatCutoff({
2015
+ value,
2016
+ locales: this.getFormattingLocales(targetLocale, locales),
2017
+ options: formatOptions
2018
+ });
2019
+ }
2020
+ formatMessage(message, targetLocale, options = {}) {
2021
+ const { locales, variables, dataFormat } = options;
2022
+ if (dataFormat === "STRING") return _formatMessageString(message);
2023
+ return _formatMessageICU(message, this.getFormattingLocales(targetLocale, locales), variables);
2024
+ }
2025
+ formatList(array, targetLocale, options = {}) {
2026
+ const { locales, ...intlOptions } = options;
2027
+ return _formatList({
2028
+ value: array,
2029
+ locales: this.getFormattingLocales(targetLocale, locales),
2030
+ options: intlOptions
2031
+ });
2032
+ }
2033
+ formatListToParts(array, targetLocale, options = {}) {
2034
+ const { locales, ...intlOptions } = options;
2035
+ return _formatListToParts({
2036
+ value: array,
2037
+ locales: this.getFormattingLocales(targetLocale, locales),
2038
+ options: intlOptions
2039
+ });
2040
+ }
2041
+ getLocaleName(locale) {
2042
+ return _getLocaleName(locale, this.defaultLocale, this.customMapping);
2043
+ }
2044
+ getLocaleEmoji(locale) {
2045
+ return _getLocaleEmoji(locale, this.customMapping);
2046
+ }
2047
+ getLocaleProperties(locale) {
2048
+ return _getLocaleProperties(locale, this.defaultLocale, this.customMapping);
2049
+ }
2050
+ requiresTranslation(targetLocale, sourceLocale = this.defaultLocale, approvedLocales = this.translationLocales) {
2051
+ return _requiresTranslation(this.resolveCanonicalLocale(sourceLocale), this.resolveCanonicalLocale(targetLocale), approvedLocales ? this.resolveCanonicalLocaleList(approvedLocales) : void 0, this.customMapping);
2052
+ }
2053
+ determineLocale(locales, approvedLocales = this.locales) {
2054
+ const approvedLocalePairs = approvedLocales.map((locale) => ({
2055
+ locale,
2056
+ canonicalLocale: this.resolveCanonicalLocale(locale)
2057
+ }));
2058
+ const resolvedLocale = _determineLocale(Array.isArray(locales) ? this.resolveCanonicalLocaleList(locales) : this.resolveCanonicalLocale(locales), approvedLocalePairs.map(({ canonicalLocale }) => canonicalLocale), this.customMapping);
2059
+ if (!resolvedLocale) return void 0;
2060
+ return approvedLocalePairs.find(({ canonicalLocale }) => canonicalLocale === resolvedLocale)?.locale || this.resolveAliasLocale(resolvedLocale);
2061
+ }
2062
+ getLocaleDirection(locale) {
2063
+ return _getLocaleDirection(this.resolveCanonicalLocale(locale));
2064
+ }
2065
+ isValidLocale(locale) {
2066
+ return _isValidLocale(locale, this.customMapping);
2067
+ }
2068
+ resolveCanonicalLocale(locale) {
2069
+ return _resolveCanonicalLocale(locale, this.customMapping);
2070
+ }
2071
+ resolveAliasLocale(locale) {
2072
+ return _resolveAliasLocale(locale, this.customMapping);
2073
+ }
2074
+ standardizeLocale(locale) {
2075
+ return _standardizeLocale(locale);
2076
+ }
2077
+ isSameDialect(...locales) {
2078
+ return _isSameDialect(...this.resolveCanonicalLocaleArgs(locales));
2079
+ }
2080
+ isSameLanguage(...locales) {
2081
+ return _isSameLanguage(...this.resolveCanonicalLocaleArgs(locales));
2082
+ }
2083
+ isSupersetLocale(superLocale, subLocale) {
2084
+ return _isSupersetLocale(this.resolveCanonicalLocale(superLocale), this.resolveCanonicalLocale(subLocale));
2085
+ }
2086
+ };
2087
+ //#endregion
2088
+ //#region src/index.ts
2089
+ /**
2090
+ * GT is the core driver for the General Translation library.
2091
+ * This class provides functionality for locale management, formatting, and translation operations.
2092
+ *
2093
+ * @class GT
2094
+ * @description A comprehensive toolkit for handling internationalization and localization.
2095
+ *
2096
+ * @example
2097
+ * const gt = new GT({
2098
+ * sourceLocale: 'en-US',
2099
+ * targetLocale: 'es-ES',
2100
+ * locales: ['en-US', 'es-ES', 'fr-FR']
2101
+ * });
2102
+ */
2103
+ var GT = class {
2104
+ /** Client-safe locale and formatting helpers */
2105
+ get localeConfig() {
2106
+ return this._localeConfig;
2107
+ }
2108
+ /**
2109
+ * Constructs an instance of the GT class.
2110
+ *
2111
+ * @param {GTConstructorParams} [params] - The parameters for initializing the GT instance
2112
+ * @throws {Error} If an invalid locale is provided
2113
+ * @throws {Error} If any of the provided locales are invalid
2114
+ *
2115
+ * @example
2116
+ * const gt = new GT({
2117
+ * apiKey: 'your-api-key',
2118
+ * sourceLocale: 'en-US',
2119
+ * targetLocale: 'es-ES',
2120
+ * locales: ['en-US', 'es-ES', 'fr-FR']
2121
+ * });
2122
+ */
2123
+ constructor(params = {}) {
2124
+ if (typeof process !== "undefined") {
2125
+ this.apiKey ||= process.env?.GT_API_KEY;
2126
+ this.devApiKey ||= process.env?.GT_DEV_API_KEY;
2127
+ this.projectId ||= process.env?.GT_PROJECT_ID;
2128
+ }
2129
+ this.setConfig(params);
2130
+ }
2131
+ setConfig({ apiKey, devApiKey, sourceLocale, targetLocale, locales, projectId, customMapping, baseUrl }) {
2132
+ if (apiKey) this.apiKey = apiKey;
2133
+ if (devApiKey) this.devApiKey = devApiKey;
2134
+ if (projectId) this.projectId = projectId;
2135
+ if (sourceLocale) {
2136
+ this.sourceLocale = _standardizeLocale(sourceLocale);
2137
+ if (!_isValidLocale(this.sourceLocale, customMapping)) throw new Error(invalidLocaleError(this.sourceLocale));
2138
+ }
2139
+ if (targetLocale) {
2140
+ this.targetLocale = _standardizeLocale(targetLocale);
2141
+ if (!_isValidLocale(this.targetLocale, customMapping)) throw new Error(invalidLocaleError(this.targetLocale));
2142
+ }
2143
+ if (locales) {
2144
+ const result = [];
2145
+ const invalidLocales = [];
2146
+ locales.forEach((locale) => {
2147
+ const standardizedLocale = _standardizeLocale(locale);
2148
+ if (_isValidLocale(standardizedLocale)) result.push(standardizedLocale);
2149
+ else invalidLocales.push(locale);
2150
+ });
2151
+ if (invalidLocales.length > 0) throw new Error(invalidLocalesError(invalidLocales));
2152
+ this.locales = result;
2153
+ }
2154
+ if (baseUrl) this.baseUrl = baseUrl;
2155
+ if (customMapping) {
2156
+ this.customMapping = customMapping;
2157
+ this.reverseCustomMapping = Object.fromEntries(Object.entries(customMapping).filter(([, value]) => value && typeof value === "object" && "code" in value).map(([key, value]) => [value.code, key]));
2158
+ }
2159
+ this._localeConfig = new LocaleConfig({
2160
+ defaultLocale: this.sourceLocale,
2161
+ locales: this.locales ?? [],
2162
+ customMapping: this.customMapping
2163
+ });
2164
+ }
2165
+ _getTranslationConfig() {
2166
+ return {
2167
+ baseUrl: this.baseUrl,
2168
+ apiKey: this.apiKey || this.devApiKey,
2169
+ projectId: this.projectId || ""
2170
+ };
2171
+ }
2172
+ _validateAuth(functionName) {
2173
+ const errors = [];
2174
+ if (!this.apiKey && !this.devApiKey) {
2175
+ const error = noApiKeyProvidedError(functionName);
2176
+ errors.push(error);
2177
+ }
2178
+ if (!this.projectId) {
2179
+ const error = noProjectIdProvidedError(functionName);
2180
+ errors.push(error);
2181
+ }
2182
+ if (errors.length) throw new Error(errors.join("\n"));
2183
+ }
2184
+ /**
2185
+ * Queries branch information from the API.
2186
+ *
2187
+ * @param {BranchQuery} query - Object mapping the current branch and incoming branches
2188
+ * @returns {Promise<BranchDataResult>} The branch information
2189
+ */
2190
+ async queryBranchData(query) {
2191
+ this._validateAuth("queryBranchData");
2192
+ return await _queryBranchData(query, this._getTranslationConfig());
2193
+ }
2194
+ /**
2195
+ * Creates a new branch in the API. If the branch already exists, it will be returned.
2196
+ *
2197
+ * @param {CreateBranchQuery} query - Object mapping the branch name and default branch flag
2198
+ * @returns {Promise<CreateBranchResult>} The created branch information
2199
+ */
2200
+ async createBranch(query) {
2201
+ this._validateAuth("createBranch");
2202
+ return await _createBranch(query, this._getTranslationConfig());
2203
+ }
2204
+ /**
2205
+ * Processes file moves by cloning source files and translations with new fileIds.
2206
+ * This is called when files have been moved/renamed and we want to preserve translations.
2207
+ *
2208
+ * @param {MoveMapping[]} moves - Array of move mappings (old fileId to new fileId)
2209
+ * @param {ProcessMovesOptions} options - Options including branchId and timeout
2210
+ * @returns {Promise<ProcessMovesResponse>} The move processing results
2211
+ *
2212
+ * @example
2213
+ * const result = await gt.processFileMoves([
2214
+ * { oldFileId: 'abc123', newFileId: 'def456', newFileName: 'locales/en.json' }
2215
+ * ], { branchId: 'main' });
2216
+ */
2217
+ async processFileMoves(moves, options = {}) {
2218
+ this._validateAuth("processFileMoves");
2219
+ return await _processFileMoves(moves, options, this._getTranslationConfig());
2220
+ }
2221
+ /**
2222
+ * Gets orphaned files for a branch - files that exist on the branch
2223
+ * but whose fileIds are not in the provided list.
2224
+ * Used for move detection.
2225
+ *
2226
+ * @param {string} branchId - The branch to check for orphaned files
2227
+ * @param {string[]} fileIds - List of current file IDs (files that are NOT orphaned)
2228
+ * @param {Object} options - Options including timeout
2229
+ * @returns {Promise<GetOrphanedFilesResult>} The orphaned files
2230
+ *
2231
+ * @example
2232
+ * const result = await gt.getOrphanedFiles('branch-id', ['file-1', 'file-2']);
2233
+ */
2234
+ async getOrphanedFiles(branchId, fileIds, options = {}) {
2235
+ this._validateAuth("getOrphanedFiles");
2236
+ return await _getOrphanedFiles(branchId, fileIds, options, this._getTranslationConfig());
2237
+ }
2238
+ /**
2239
+ * Enqueues project setup job using the specified file references
2240
+ *
2241
+ * This method creates setup jobs that will process source file references
2242
+ * and generate a project setup. The files parameter contains references (IDs) to source
2243
+ * files that have already been uploaded via uploadSourceFiles. The setup jobs are queued
2244
+ * for processing and will generate a project setup based on the source files.
2245
+ *
2246
+ * @param {FileReference[]} files - Array of file references containing IDs of previously uploaded source files
2247
+ * @param {SetupProjectOptions} [options] - Optional settings for target locales and timeout
2248
+ * @returns {Promise<SetupProjectResult>} Object containing the jobId and status
2249
+ */
2250
+ async setupProject(files, options) {
2251
+ this._validateAuth("setupProject");
2252
+ options = {
2253
+ ...options,
2254
+ locales: options?.locales?.map((locale) => this.resolveCanonicalLocale(locale))
2255
+ };
2256
+ return await _setupProject(files, this._getTranslationConfig(), options);
2257
+ }
2258
+ /**
2259
+ * Checks the current status of one or more project jobs by their unique identifiers.
2260
+ *
2261
+ * This method polls the API to determine whether one or more jobs are still running,
2262
+ * have completed successfully, or have failed. Jobs are created after calling either enqueueFiles or setupProject.
2263
+ *
2264
+ * @param {string[]} jobIds - The unique identifiers of the jobs to check
2265
+ * @param {number} [timeoutMs] - Optional timeout in milliseconds for the API request
2266
+ * @returns {Promise<CheckJobStatusResult>} Object containing the job status
2267
+ *
2268
+ * @example
2269
+ * const result = await gt.checkJobStatus([
2270
+ * 'job-123',
2271
+ * 'job-456',
2272
+ * ], {
2273
+ * timeout: 10000,
2274
+ * });
2275
+ */
2276
+ async checkJobStatus(jobIds, timeoutMs) {
2277
+ this._validateAuth("checkJobStatus");
2278
+ return await _checkJobStatus(jobIds, this._getTranslationConfig(), timeoutMs);
2279
+ }
2280
+ /**
2281
+ * Polls job statuses until all jobs from enqueueFiles are finished or the timeout is reached.
2282
+ *
2283
+ * @param {EnqueueFilesResult} enqueueResult - The result returned from enqueueFiles
2284
+ * @param {AwaitJobsOptions} [options] - Polling configuration (interval, timeout)
2285
+ * @returns {Promise<AwaitJobsResult>} The final status of all jobs and whether they all completed
2286
+ */
2287
+ async awaitJobs(enqueueResult, options) {
2288
+ this._validateAuth("awaitJobs");
2289
+ return await _awaitJobs(enqueueResult, options, this._getTranslationConfig());
2290
+ }
2291
+ /**
2292
+ * Enqueues translation jobs for previously uploaded source files.
2293
+ *
2294
+ * This method creates translation jobs that will process existing source files
2295
+ * and generate translations in the specified target languages. The files parameter
2296
+ * contains references (IDs) to source files that have already been uploaded via
2297
+ * uploadSourceFiles. The translation jobs are queued for processing and will
2298
+ * generate translated content based on the source files and target locales provided.
2299
+ *
2300
+ * @param {FileReferenceIds[]} files - Array of file references containing IDs of previously uploaded source files
2301
+ * @param {EnqueueOptions} options - Configuration options including source locale, target locales, and job settings
2302
+ * @returns {Promise<EnqueueFilesResult>} Result containing job IDs, queue status, and processing information
2303
+ */
2304
+ async enqueueFiles(files, options) {
2305
+ this._validateAuth("enqueueFiles");
2306
+ let mergedOptions = {
2307
+ ...options,
2308
+ sourceLocale: options.sourceLocale ?? this.sourceLocale,
2309
+ targetLocales: options.targetLocales ?? [this.targetLocale]
2310
+ };
2311
+ if (!mergedOptions.sourceLocale) {
2312
+ const error = noSourceLocaleProvidedError("enqueueFiles");
2313
+ gtInstanceLogger.error(error);
2314
+ throw new Error(error);
2315
+ }
2316
+ if (!mergedOptions.targetLocales || mergedOptions.targetLocales.length === 0) {
2317
+ const error = noTargetLocaleProvidedError("enqueueFiles");
2318
+ gtInstanceLogger.error(error);
2319
+ throw new Error(error);
2320
+ }
2321
+ mergedOptions = {
2322
+ ...mergedOptions,
2323
+ targetLocales: mergedOptions.targetLocales.map((locale) => this.resolveCanonicalLocale(locale))
2324
+ };
2325
+ return await _enqueueFiles(files, mergedOptions, this._getTranslationConfig());
2326
+ }
2327
+ /**
2328
+ * Creates or upserts a file tag, associating a set of source files
2329
+ * with a user-defined tag ID and optional message.
2330
+ *
2331
+ * @param {CreateTagOptions} options - Tag creation options including tagId, sourceFileIds, and optional message
2332
+ * @returns {Promise<CreateTagResult>} The created or updated tag
2333
+ */
2334
+ async createTag(options) {
2335
+ this._validateAuth("createTag");
2336
+ return await _createTag(options, this._getTranslationConfig());
2337
+ }
2338
+ /**
2339
+ * Publishes or unpublishes files on the CDN.
2340
+ *
2341
+ * @param {PublishFileEntry[]} files - Array of file entries with publish flags
2342
+ * @returns {Promise<PublishFilesResult>} Result containing per-file success/failure
2343
+ */
2344
+ async publishFiles(files) {
2345
+ this._validateAuth("publishFiles");
2346
+ return await _publishFiles(files, this._getTranslationConfig());
2347
+ }
2348
+ /**
2349
+ * Submits user edit diffs for existing translations so future generations preserve user intent.
2350
+ *
2351
+ * @param {SubmitUserEditDiffsPayload} payload - Project-scoped diff payload.
2352
+ * @returns {Promise<void>} Resolves when submission succeeds.
2353
+ */
2354
+ async submitUserEditDiffs(payload) {
2355
+ this._validateAuth("submitUserEditDiffs");
2356
+ await _submitUserEditDiffs({
2357
+ ...payload,
2358
+ diffs: (payload.diffs || []).map((d) => ({
2359
+ ...d,
2360
+ locale: this.resolveCanonicalLocale(d.locale)
2361
+ }))
2362
+ }, this._getTranslationConfig());
2363
+ }
2364
+ /**
2365
+ * Queries data about one or more source or translation files.
2366
+ *
2367
+ * @param {FileDataQuery} data - Object mapping source and translation file information.
2368
+ * @param {CheckFileTranslationsOptions} options - Options for the API call.
2369
+ * @returns {Promise<FileDataResult>} The source and translation file data information.
2370
+ *
2371
+ * @example
2372
+ * const result = await gt.queryFileData({
2373
+ * sourceFiles: [
2374
+ * { fileId: '1234567890', versionId: '1234567890', branchId: '1234567890' },
2375
+ * ],
2376
+ * translatedFiles: [
2377
+ * { fileId: '1234567890', versionId: '1234567890', branchId: '1234567890', locale: 'es-ES' },
2378
+ * ],
2379
+ * }, {
2380
+ * timeout: 10000,
2381
+ * });
2382
+ *
2383
+ */
2384
+ async queryFileData(data, options = {}) {
2385
+ this._validateAuth("queryFileData");
2386
+ data.translatedFiles = data.translatedFiles?.map((item) => ({
2387
+ ...item,
2388
+ locale: this.resolveCanonicalLocale(item.locale)
2389
+ }));
2390
+ const result = await _queryFileData(data, options, this._getTranslationConfig());
2391
+ result.translatedFiles = result.translatedFiles?.map((item) => ({
2392
+ ...item,
2393
+ ...item.locale && { locale: this.resolveAliasLocale(item.locale) }
2394
+ }));
2395
+ result.sourceFiles = result.sourceFiles?.map((item) => ({
2396
+ ...item,
2397
+ ...item.sourceLocale && { sourceLocale: this.resolveAliasLocale(item.sourceLocale) },
2398
+ locales: item.locales.map((locale) => this.resolveAliasLocale(locale))
2399
+ }));
2400
+ return result;
2401
+ }
2402
+ /**
2403
+ * Gets source and translation information for a given file ID and version ID.
2404
+ *
2405
+ * @param {FileQuery} data - File query containing file ID and version ID.
2406
+ * @param {CheckFileTranslationsOptions} options - Options for getting source and translation information.
2407
+ * @returns {Promise<FileQueryResult>} The source file and translation information.
2408
+ *
2409
+ * @example
2410
+ * const result = await gt.querySourceFile(
2411
+ * { fileId: '1234567890', versionId: '1234567890' },
2412
+ * { timeout: 10000 }
2413
+ * );
2414
+ *
2415
+ */
2416
+ async querySourceFile(data, options = {}) {
2417
+ this._validateAuth("querySourceFile");
2418
+ const result = await _querySourceFile(data, options, this._getTranslationConfig());
2419
+ result.translations = result.translations.map((item) => ({
2420
+ ...item,
2421
+ ...item.locale && { locale: this.resolveAliasLocale(item.locale) }
2422
+ }));
2423
+ result.sourceFile.locales = result.sourceFile.locales.map((locale) => this.resolveAliasLocale(locale));
2424
+ if (result.sourceFile.sourceLocale) result.sourceFile.sourceLocale = this.resolveAliasLocale(result.sourceFile.sourceLocale);
2425
+ return result;
2426
+ }
2427
+ /**
2428
+ * Get project data for a given project ID.
2429
+ *
2430
+ * @param {string} projectId - The ID of the project to get the data for.
2431
+ * @returns {Promise<ProjectData>} The project data.
2432
+ *
2433
+ * @example
2434
+ * const result = await gt.getProjectData(
2435
+ * '1234567890'
2436
+ * );
2437
+ *
2438
+ */
2439
+ async getProjectData(projectId, options = {}) {
2440
+ this._validateAuth("getProjectData");
2441
+ const result = await _getProjectData(projectId, options, this._getTranslationConfig());
2442
+ result.currentLocales = result.currentLocales.map((item) => this.resolveAliasLocale(item));
2443
+ result.defaultLocale = this.resolveAliasLocale(result.defaultLocale);
2444
+ return result;
2445
+ }
2446
+ /**
2447
+ * Downloads a single file.
2448
+ *
2449
+ * @param file - The file query object.
2450
+ * @param {string} file.fileId - The ID of the file to download.
2451
+ * @param {string} [file.branchId] - The ID of the branch to download the file from. If not provided, the default branch will be used.
2452
+ * @param {string} [file.locale] - The locale to download the file for. If not provided, the source file will be downloaded.
2453
+ * @param {string} [file.versionId] - The version ID to download the file from. If not provided, the latest version will be used.
2454
+ * @param {DownloadFileOptions} options - Options for downloading the file.
2455
+ * @returns {Promise<string>} The downloaded file content.
2456
+ *
2457
+ * @example
2458
+ * const result = await gt.downloadFile({
2459
+ * fileId: '1234567890',
2460
+ * branchId: '1234567890',
2461
+ * locale: 'es-ES',
2462
+ * versionId: '1234567890',
2463
+ * }, {
2464
+ * timeout: 10000,
2465
+ * });
2466
+ */
2467
+ async downloadFile(file, options = {}) {
2468
+ this._validateAuth("downloadTranslatedFile");
2469
+ return (await _downloadFileBatch([{
2470
+ fileId: file.fileId,
2471
+ branchId: file.branchId,
2472
+ locale: file.locale ? this.resolveCanonicalLocale(file.locale) : void 0,
2473
+ versionId: file.versionId,
2474
+ useLatestAvailableVersion: file.useLatestAvailableVersion
2475
+ }], options, this._getTranslationConfig())).data?.[0]?.data ?? "";
2476
+ }
2477
+ /**
2478
+ * Downloads multiple files in a batch.
2479
+ *
2480
+ * @param {DownloadFileBatchRequest} requests - Array of file query objects to download.
2481
+ * @param {DownloadFileBatchOptions} options - Options for the batch download.
2482
+ * @returns {Promise<DownloadFileBatchResult>} The batch download results.
2483
+ *
2484
+ * @example
2485
+ * const result = await gt.downloadFileBatch([{
2486
+ * fileId: '1234567890',
2487
+ * locale: 'es-ES',
2488
+ * versionId: '1234567890',
2489
+ * }], {
2490
+ * timeout: 10000,
2491
+ * });
2492
+ */
2493
+ async downloadFileBatch(requests, options = {}) {
2494
+ this._validateAuth("downloadFileBatch");
2495
+ requests = requests.map((request) => ({
2496
+ ...request,
2497
+ locale: request.locale ? this.resolveCanonicalLocale(request.locale) : void 0
2498
+ }));
2499
+ const result = await _downloadFileBatch(requests, options, this._getTranslationConfig());
2500
+ return {
2501
+ files: result.data.map((file) => ({
2502
+ ...file,
2503
+ ...file.locale && { locale: this.resolveAliasLocale(file.locale) }
2504
+ })),
2505
+ count: result.count
2506
+ };
2507
+ }
2508
+ /**
2509
+ * Translates a single source string to the target locale.
2510
+ * Routes through {@link translateMany} under the hood.
2511
+ *
2512
+ * @param {string} source - The source string to translate.
2513
+ * @param {object} options - Translation options including targetLocale and optional entry metadata.
2514
+ * @returns {Promise<TranslationResult | TranslationError>} The translated content.
2515
+ *
2516
+ * @example
2517
+ * const result = await gt.translate('Hello, world!', { targetLocale: 'es' });
2518
+ *
2519
+ * @example
2520
+ * const result = await gt.translate('Hello, world!', {
2521
+ * targetLocale: 'es',
2522
+ * dataFormat: 'ICU',
2523
+ * context: 'A formal greeting',
2524
+ * });
2525
+ */
2526
+ async translate(source, options, timeout) {
2527
+ if (typeof options === "string") options = { targetLocale: options };
2528
+ this._validateAuth("translate");
2529
+ let targetLocale = options?.targetLocale || this.targetLocale;
2530
+ if (!targetLocale) {
2531
+ const error = noTargetLocaleProvidedError("translate");
2532
+ gtInstanceLogger.error(error);
2533
+ throw new Error(error);
2534
+ }
2535
+ targetLocale = this.resolveCanonicalLocale(targetLocale);
2536
+ const sourceLocale = this.resolveCanonicalLocale(options?.sourceLocale || this.sourceLocale || "en");
2537
+ return (await _translateMany([source], {
2538
+ ...options,
2539
+ targetLocale,
2540
+ sourceLocale
2541
+ }, this._getTranslationConfig(), timeout))[0];
2542
+ }
2543
+ async translateMany(sources, options, timeout) {
2544
+ if (typeof options === "string") options = { targetLocale: options };
2545
+ this._validateAuth("translateMany");
2546
+ let targetLocale = options?.targetLocale || this.targetLocale;
2547
+ if (!targetLocale) {
2548
+ const error = noTargetLocaleProvidedError("translateMany");
2549
+ gtInstanceLogger.error(error);
2550
+ throw new Error(error);
2551
+ }
2552
+ targetLocale = this.resolveCanonicalLocale(targetLocale);
2553
+ const sourceLocale = this.resolveCanonicalLocale(options?.sourceLocale || this.sourceLocale || "en");
2554
+ return await _translateMany(sources, {
2555
+ ...options,
2556
+ targetLocale,
2557
+ sourceLocale
2558
+ }, this._getTranslationConfig(), timeout);
2559
+ }
2560
+ /**
2561
+ * Uploads source files to the translation service without any translation content.
2562
+ *
2563
+ * This method creates or replaces source file entries in your project. Each uploaded
2564
+ * file becomes a source that can later be translated into target languages. The files
2565
+ * are processed and stored as base entries that serve as the foundation for generating
2566
+ * translations through the translation workflow.
2567
+ *
2568
+ * @param {Array<{source: FileUpload}>} files - Array of objects containing source file data to upload
2569
+ * @param {UploadFilesOptions} options - Configuration options including source locale and other upload settings
2570
+ * @returns {Promise<UploadFilesResponse>} Upload result containing file IDs, version information, and upload status
2571
+ */
2572
+ async uploadSourceFiles(files, options) {
2573
+ this._validateAuth("uploadSourceFiles");
2574
+ const mergedOptions = {
2575
+ ...options,
2576
+ sourceLocale: this.resolveCanonicalLocale(options.sourceLocale ?? this.sourceLocale ?? "en")
2577
+ };
2578
+ files = files.map((f) => ({
2579
+ ...f,
2580
+ source: {
2581
+ ...f.source,
2582
+ locale: this.resolveCanonicalLocale(f.source.locale)
2583
+ }
2584
+ }));
2585
+ const result = await _uploadSourceFiles(files, mergedOptions, this._getTranslationConfig());
2586
+ return {
2587
+ uploadedFiles: result.data,
2588
+ count: result.count,
2589
+ message: `Successfully uploaded ${result.count} files in ${result.batchCount} batch(es)`
2590
+ };
2591
+ }
2592
+ /**
2593
+ * Uploads translation files that correspond to previously uploaded source files.
2594
+ *
2595
+ * This method allows you to provide translated content for existing source files in your project.
2596
+ * Each translation must reference an existing source file and include the translated content
2597
+ * along with the target locale information. This is used when you have pre-existing translations
2598
+ * that you want to upload directly rather than generating them through the translation service.
2599
+ *
2600
+ * @param {Array<{source: FileUpload, translations: FileUpload[]}>} files - Array of file objects where:
2601
+ * - `source`: Reference to the existing source file (contains IDs but no content)
2602
+ * - `translations`: Array of translated files, each containing content, locale, and reference IDs
2603
+ * @param {UploadFilesOptions} options - Configuration options including source locale and upload settings
2604
+ * @returns {Promise<UploadFilesResponse>} Upload result containing translation IDs, status, and processing information
2605
+ */
2606
+ async uploadTranslations(files, options) {
2607
+ this._validateAuth("uploadTranslations");
2608
+ const mergedOptions = {
2609
+ ...options,
2610
+ sourceLocale: options.sourceLocale ?? this.sourceLocale
2611
+ };
2612
+ if (!mergedOptions.sourceLocale) {
2613
+ const error = noSourceLocaleProvidedError("uploadTranslations");
2614
+ gtInstanceLogger.error(error);
2615
+ throw new Error(error);
2616
+ }
2617
+ const result = await _uploadTranslations(files.map((f) => ({
2618
+ ...f,
2619
+ translations: f.translations.map((t) => ({
2620
+ ...t,
2621
+ locale: this.resolveCanonicalLocale(t.locale)
2622
+ }))
2623
+ })), mergedOptions, this._getTranslationConfig());
2624
+ return {
2625
+ uploadedFiles: result.data,
2626
+ count: result.count,
2627
+ message: `Successfully uploaded ${result.count} files in ${result.batchCount} batch(es)`
2628
+ };
2629
+ }
2630
+ /**
2631
+ * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.
2632
+ *
2633
+ * This method uses the GT instance's rendering locales by default for locale-specific terminator selection,
2634
+ * but can be overridden with custom locales in the options.
2635
+ *
2636
+ * @param {string} value - The string value to format with cutoff behavior.
2637
+ * @param {Object} [options] - Configuration options for cutoff formatting.
2638
+ * @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales.
2639
+ * @param {number} [options.maxChars] - The maximum number of characters to display.
2640
+ * - Undefined values are treated as no cutoff.
2641
+ * - Negative values follow .slice() behavior and terminator will be added before the value.
2642
+ * - 0 will result in an empty string.
2643
+ * - If cutoff results in an empty string, no terminator is added.
2644
+ * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.
2645
+ * @param {string} [options.terminator] - Optional override the terminator to use.
2646
+ * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.
2647
+ * - If no terminator is provided, then separator is ignored.
2648
+ * @returns {string} The formatted string with terminator applied if cutoff occurs.
2649
+ *
2650
+ * @example
2651
+ * const gt = new GT({ targetLocale: 'en-US' });
2652
+ * gt.formatCutoff('Hello, world!', { maxChars: 8 });
2653
+ * // Returns: 'Hello, w...'
2654
+ *
2655
+ * @example
2656
+ * gt.formatCutoff('Hello, world!', { maxChars: -3 });
2657
+ * // Returns: '...ld!'
2658
+ */
2659
+ formatCutoff(value, options) {
2660
+ return this.localeConfig.formatCutoff(value, this.targetLocale, options);
2661
+ }
2662
+ /**
2663
+ * Formats a message according to the specified locales and options.
2664
+ *
2665
+ * @param {string} message - The message to format.
2666
+ * @param {string | string[]} [locales='en'] - The locales to use for formatting.
2667
+ * @param {FormatVariables} [variables={}] - The variables to use for formatting.
2668
+ * @param {StringFormat} [dataFormat='ICU'] - The format of the message.
2669
+ * @returns {string} The formatted message.
2670
+ *
2671
+ * @example
2672
+ * gt.formatMessage('Hello {name}', { name: 'John' });
2673
+ * // Returns: "Hello John"
2674
+ *
2675
+ * gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });
2676
+ * // Returns: "Bonjour John"
2677
+ */
2678
+ formatMessage(message, options) {
2679
+ return this.localeConfig.formatMessage(message, this.targetLocale, options);
2680
+ }
2681
+ /**
2682
+ * Formats a number according to the specified locales and options.
2683
+ *
2684
+ * @param {number} number - The number to format
2685
+ * @param {Object} [options] - Additional options for number formatting
2686
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2687
+ * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options
2688
+ * @returns {string} The formatted number
2689
+ *
2690
+ * @example
2691
+ * gt.formatNum(1234.56, { style: 'currency', currency: 'USD' });
2692
+ * // Returns: "$1,234.56"
2693
+ */
2694
+ formatNum(number, options) {
2695
+ return this.localeConfig.formatNum(number, this.targetLocale, options);
2696
+ }
2697
+ /**
2698
+ * Formats a date according to the specified locales and options.
2699
+ *
2700
+ * @param {Date} date - The date to format
2701
+ * @param {Object} [options] - Additional options for date formatting
2702
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2703
+ * @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options
2704
+ * @returns {string} The formatted date
2705
+ *
2706
+ * @example
2707
+ * gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' });
2708
+ * // Returns: "Thursday, March 14, 2024 at 2:30:45 PM GMT-7"
2709
+ */
2710
+ formatDateTime(date, options) {
2711
+ return this.localeConfig.formatDateTime(date, this.targetLocale, options);
2712
+ }
2713
+ /**
2714
+ * Formats a currency value according to the specified locales and options.
2715
+ *
2716
+ * @param {number} value - The currency value to format
2717
+ * @param {string} currency - The currency code (e.g., 'USD', 'EUR')
2718
+ * @param {Object} [options] - Additional options for currency formatting
2719
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2720
+ * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options
2721
+ * @returns {string} The formatted currency value
2722
+ *
2723
+ * @example
2724
+ * gt.formatCurrency(1234.56, 'USD', { style: 'currency' });
2725
+ * // Returns: "$1,234.56"
2726
+ */
2727
+ formatCurrency(value, currency, options) {
2728
+ return this.localeConfig.formatCurrency(value, currency, this.targetLocale, options);
2729
+ }
2730
+ /**
2731
+ * Formats a list of items according to the specified locales and options.
2732
+ *
2733
+ * @param {Array<string | number>} array - The list of items to format
2734
+ * @param {Object} [options] - Additional options for list formatting
2735
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2736
+ * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options
2737
+ * @returns {string} The formatted list
2738
+ *
2739
+ * @example
2740
+ * gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' });
2741
+ * // Returns: "apple, banana, and orange"
2742
+ */
2743
+ formatList(array, options) {
2744
+ return this.localeConfig.formatList(array, this.targetLocale, options);
2745
+ }
2746
+ /**
2747
+ * Formats a list of items according to the specified locales and options.
2748
+ * @param {Array<T>} array - The list of items to format
2749
+ * @param {Object} [options] - Additional options for list formatting
2750
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2751
+ * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options
2752
+ * @returns {Array<T | string>} The formatted list parts
2753
+ *
2754
+ * @example
2755
+ * gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] });
2756
+ * // Returns: ['apple', ', ', 42, ' and ', '{ foo: "bar" }']
2757
+ */
2758
+ formatListToParts(array, options) {
2759
+ return this.localeConfig.formatListToParts(array, this.targetLocale, options);
2760
+ }
2761
+ /**
2762
+ * Formats a relative time value according to the specified locales and options.
2763
+ *
2764
+ * @param {number} value - The relative time value to format
2765
+ * @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year')
2766
+ * @param {Object} options - Additional options for relative time formatting
2767
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2768
+ * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options
2769
+ * @returns {string} The formatted relative time string
2770
+ *
2771
+ * @example
2772
+ * gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' });
2773
+ * // Returns: "yesterday"
2774
+ */
2775
+ formatRelativeTime(value, unit, options) {
2776
+ return this.localeConfig.formatRelativeTime(value, unit, this.targetLocale, options);
2777
+ }
2778
+ /**
2779
+ * Formats a relative time string from a Date, automatically selecting the best unit.
2780
+ *
2781
+ * @param {Date} date - The date to format relative to now
2782
+ * @param {Object} [options] - Additional options for relative time formatting
2783
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2784
+ * @returns {string} The formatted relative time string (e.g., "2 hours ago", "in 3 days")
2785
+ *
2786
+ * @example
2787
+ * gt.formatRelativeTimeFromDate(new Date(Date.now() - 3600000));
2788
+ * // Returns: "1 hour ago"
2789
+ */
2790
+ formatRelativeTimeFromDate(date, options) {
2791
+ return this.localeConfig.formatRelativeTimeFromDate(date, this.targetLocale, options);
2792
+ }
2793
+ /**
2794
+ * Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found.
2795
+ *
2796
+ * @param {string} [locale=this.targetLocale] - A BCP-47 locale code
2797
+ * @returns {string} The display name corresponding to the code
2798
+ * @throws {Error} If no target locale is provided
2799
+ *
2800
+ * @example
2801
+ * gt.getLocaleName('es-ES');
2802
+ * // Returns: "Spanish (Spain)"
2803
+ */
2804
+ getLocaleName(locale = this.targetLocale) {
2805
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleName"));
2806
+ return this.localeConfig.getLocaleName(locale);
2807
+ }
2808
+ /**
2809
+ * Retrieves an emoji based on a given locale code.
2810
+ * Uses the locale's region (if present) to select an emoji or falls back on default emojis.
2811
+ *
2812
+ * @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA')
2813
+ * @returns {string} The emoji representing the locale or its region
2814
+ * @throws {Error} If no target locale is provided
2815
+ *
2816
+ * @example
2817
+ * gt.getLocaleEmoji('es-ES');
2818
+ * // Returns: "🇪🇸"
2819
+ */
2820
+ getLocaleEmoji(locale = this.targetLocale) {
2821
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleEmoji"));
2822
+ return this.localeConfig.getLocaleEmoji(locale);
2823
+ }
2824
+ /**
2825
+ * Generates linguistic details for a given locale code.
2826
+ *
2827
+ * This function returns information about the locale,
2828
+ * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).
2829
+ * The function provides these names in both your default language and native forms, and an associated emoji.
2830
+ *
2831
+ * @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., "de-AT").
2832
+ * @returns {LocaleProperties} - An object containing detailed information about the locale.
2833
+ *
2834
+ * @property {string} code - The full locale code, e.g., "de-AT".
2835
+ * @property {string} name - Language name in the default display language, e.g., "Austrian German".
2836
+ * @property {string} nativeName - Language name in the locale's native language, e.g., "Österreichisches Deutsch".
2837
+ * @property {string} languageCode - The base language code, e.g., "de".
2838
+ * @property {string} languageName - The language name in the default display language, e.g., "German".
2839
+ * @property {string} nativeLanguageName - The language name in the native language, e.g., "Deutsch".
2840
+ * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., "German (AT)".
2841
+ * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., "Deutsch (AT)".
2842
+ * @property {string} regionCode - The region code from maximization, e.g., "AT".
2843
+ * @property {string} regionName - The region name in the default display language, e.g., "Austria".
2844
+ * @property {string} nativeRegionName - The region name in the native language, e.g., "Österreich".
2845
+ * @property {string} scriptCode - The script code from maximization, e.g., "Latn".
2846
+ * @property {string} scriptName - The script name in the default display language, e.g., "Latin".
2847
+ * @property {string} nativeScriptName - The script name in the native language, e.g., "Lateinisch".
2848
+ * @property {string} maximizedCode - The maximized locale code, e.g., "de-Latn-AT".
2849
+ * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., "Austrian German (Latin)".
2850
+ * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., "Österreichisches Deutsch (Lateinisch)".
2851
+ * @property {string} minimizedCode - Minimized locale code, e.g., "de-AT" (or "de" for "de-DE").
2852
+ * @property {string} minimizedName - Minimized language name in the default language, e.g., "Austrian German".
2853
+ * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., "Österreichisches Deutsch".
2854
+ * @property {string} emoji - The emoji associated with the locale's region, if applicable.
2855
+ */
2856
+ getLocaleProperties(locale = this.targetLocale) {
2857
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleProperties"));
2858
+ return this.localeConfig.getLocaleProperties(locale);
2859
+ }
2860
+ /**
2861
+ * Retrieves multiple properties for a given region code, including:
2862
+ * - `code`: the original region code
2863
+ * - `name`: the localized display name
2864
+ * - `emoji`: the associated flag or symbol
2865
+ *
2866
+ * Behavior:
2867
+ * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
2868
+ * - Uses the instance's `targetLocale` to localize the region name for the user.
2869
+ * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
2870
+ * - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`.
2871
+ * - Falls back to the region code as `name` if display name resolution fails.
2872
+ * - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`.
2873
+ *
2874
+ * @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
2875
+ * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
2876
+ * @returns {{ code: string, name: string, emoji: string }} An object containing:
2877
+ * - `code`: the input region code
2878
+ * - `name`: the localized or custom region name
2879
+ * - `emoji`: the matching emoji flag or symbol
2880
+ *
2881
+ * @throws {Error} If no target locale is available to determine region properties.
2882
+ *
2883
+ * @example
2884
+ * const gt = new GT({ targetLocale: 'en-US' });
2885
+ * gt.getRegionProperties('US');
2886
+ * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
2887
+ *
2888
+ * @example
2889
+ * const gt = new GT({ targetLocale: 'fr-FR' });
2890
+ * gt.getRegionProperties('US');
2891
+ * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
2892
+ *
2893
+ * @example
2894
+ * gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } });
2895
+ * // => { code: 'US', name: 'USA', emoji: '🗽' }
2896
+ */
2897
+ getRegionProperties(region = this.getLocaleProperties().regionCode, customMapping) {
2898
+ if (!customMapping) {
2899
+ if (this.customMapping && !this.customRegionMapping) {
2900
+ const customRegionMapping = {};
2901
+ for (const [locale, lp] of Object.entries(this.customMapping)) if (lp && typeof lp === "object" && lp.regionCode && !customRegionMapping[lp.regionCode]) {
2902
+ const { regionName: name, emoji } = lp;
2903
+ customRegionMapping[lp.regionCode] = {
2904
+ locale,
2905
+ ...name && { name },
2906
+ ...emoji && { emoji }
2907
+ };
2908
+ }
2909
+ this.customRegionMapping = customRegionMapping;
2910
+ }
2911
+ customMapping = this.customRegionMapping;
2912
+ }
2913
+ return _getRegionProperties(region, this.targetLocale, customMapping);
2914
+ }
2915
+ /**
2916
+ * Determines whether a translation is required based on the source and target locales.
2917
+ *
2918
+ * @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content
2919
+ * @param {string} [targetLocale=this.targetLocale] - The locale code to translate into
2920
+ * @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales
2921
+ * @returns {boolean} True if translation is required, false otherwise
2922
+ * @throws {Error} If no source locale is provided
2923
+ * @throws {Error} If no target locale is provided
2924
+ *
2925
+ * @example
2926
+ * gt.requiresTranslation('en-US', 'es-ES');
2927
+ * // Returns: true
2928
+ */
2929
+ requiresTranslation(sourceLocale = this.sourceLocale, targetLocale = this.targetLocale, approvedLocales = this.locales, customMapping = this.customMapping) {
2930
+ if (!sourceLocale) throw new Error(noSourceLocaleProvidedError("requiresTranslation"));
2931
+ if (!targetLocale) throw new Error(noTargetLocaleProvidedError("requiresTranslation"));
2932
+ if (customMapping === this.customMapping) return this.localeConfig.requiresTranslation(targetLocale, sourceLocale, approvedLocales);
2933
+ return _requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping);
2934
+ }
2935
+ /**
2936
+ * Determines the best matching locale from the provided approved locales list.
2937
+ *
2938
+ * @param {string | string[]} locales - A single locale or array of locales in preference order
2939
+ * @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order
2940
+ * @returns {string | undefined} The best matching locale or undefined if no match is found
2941
+ *
2942
+ * @example
2943
+ * gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']);
2944
+ * // Returns: "fr-FR"
2945
+ */
2946
+ determineLocale(locales, approvedLocales = this.locales || [], customMapping = this.customMapping) {
2947
+ if (customMapping === this.customMapping) return this.localeConfig.determineLocale(locales, approvedLocales ?? []);
2948
+ return _determineLocale(locales, approvedLocales, customMapping);
2949
+ }
2950
+ /**
2951
+ * Gets the text direction for a given locale code.
2952
+ *
2953
+ * @param {string} [locale=this.targetLocale] - A BCP-47 locale code
2954
+ * @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left, otherwise 'ltr'
2955
+ * @throws {Error} If no target locale is provided
2956
+ *
2957
+ * @example
2958
+ * gt.getLocaleDirection('ar-SA');
2959
+ * // Returns: "rtl"
2960
+ */
2961
+ getLocaleDirection(locale = this.targetLocale) {
2962
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleDirection"));
2963
+ return this.localeConfig.getLocaleDirection(locale);
2964
+ }
2965
+ /**
2966
+ * Checks if a given BCP 47 locale code is valid.
2967
+ *
2968
+ * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate
2969
+ * @param {customMapping} [customMapping=this.customMapping] - The custom mapping to use for validation
2970
+ * @returns {boolean} True if the locale code is valid, false otherwise
2971
+ * @throws {Error} If no target locale is provided
2972
+ *
2973
+ * @example
2974
+ * gt.isValidLocale('en-US');
2975
+ * // Returns: true
2976
+ */
2977
+ isValidLocale(locale = this.targetLocale, customMapping = this.customMapping) {
2978
+ if (!locale) throw new Error(noTargetLocaleProvidedError("isValidLocale"));
2979
+ if (customMapping === this.customMapping) return this.localeConfig.isValidLocale(locale);
2980
+ return _isValidLocale(locale, customMapping);
2981
+ }
2982
+ /**
2983
+ * Resolves the canonical locale for a given locale.
2984
+ * @param locale - The locale to resolve the canonical locale for
2985
+ * @param customMapping - The custom mapping to use for resolving the canonical locale
2986
+ * @returns The canonical locale
2987
+ */
2988
+ resolveCanonicalLocale(locale = this.targetLocale, customMapping = this.customMapping) {
2989
+ if (!locale) throw new Error(noTargetLocaleProvidedError("resolveCanonicalLocale"));
2990
+ if (customMapping === this.customMapping) return this.localeConfig.resolveCanonicalLocale(locale);
2991
+ return _resolveCanonicalLocale(locale, customMapping);
2992
+ }
2993
+ /**
2994
+ * Resolves the alias locale for a given locale.
2995
+ * @param locale - The locale to resolve the alias locale for
2996
+ * @param customMapping - The custom mapping to use for resolving the alias locale
2997
+ * @returns The alias locale
2998
+ */
2999
+ resolveAliasLocale(locale, customMapping = this.customMapping) {
3000
+ if (!locale) throw new Error(noTargetLocaleProvidedError("resolveAliasLocale"));
3001
+ if (customMapping === this.customMapping) return this.localeConfig.resolveAliasLocale(locale);
3002
+ return _resolveAliasLocale(locale, customMapping);
3003
+ }
3004
+ /**
3005
+ * Standardizes a BCP 47 locale code to ensure correct formatting.
3006
+ *
3007
+ * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize
3008
+ * @returns {string} The standardized locale code or empty string if invalid
3009
+ * @throws {Error} If no target locale is provided
3010
+ *
3011
+ * @example
3012
+ * gt.standardizeLocale('en_us');
3013
+ * // Returns: "en-US"
3014
+ */
3015
+ standardizeLocale(locale = this.targetLocale) {
3016
+ if (!locale) throw new Error(noTargetLocaleProvidedError("standardizeLocale"));
3017
+ return this.localeConfig.standardizeLocale(locale);
3018
+ }
3019
+ /**
3020
+ * Checks if multiple BCP 47 locale codes represent the same dialect.
3021
+ *
3022
+ * @param {...(string | string[])} locales - The BCP 47 locale codes to compare
3023
+ * @returns {boolean} True if all codes represent the same dialect, false otherwise
3024
+ *
3025
+ * @example
3026
+ * gt.isSameDialect('en-US', 'en-GB');
3027
+ * // Returns: false
3028
+ *
3029
+ * gt.isSameDialect('en', 'en-US');
3030
+ * // Returns: true
3031
+ */
3032
+ isSameDialect(...locales) {
3033
+ return this.localeConfig.isSameDialect(...locales);
3034
+ }
3035
+ /**
3036
+ * Checks if multiple BCP 47 locale codes represent the same language.
3037
+ *
3038
+ * @param {...(string | string[])} locales - The BCP 47 locale codes to compare
3039
+ * @returns {boolean} True if all codes represent the same language, false otherwise
3040
+ *
3041
+ * @example
3042
+ * gt.isSameLanguage('en-US', 'en-GB');
3043
+ * // Returns: true
3044
+ */
3045
+ isSameLanguage(...locales) {
3046
+ return this.localeConfig.isSameLanguage(...locales);
3047
+ }
3048
+ /**
3049
+ * Checks if a locale is a superset of another locale.
3050
+ *
3051
+ * @param {string} superLocale - The locale to check if it is a superset
3052
+ * @param {string} subLocale - The locale to check if it is a subset
3053
+ * @returns {boolean} True if superLocale is a superset of subLocale, false otherwise
3054
+ *
3055
+ * @example
3056
+ * gt.isSupersetLocale('en', 'en-US');
3057
+ * // Returns: true
3058
+ *
3059
+ * gt.isSupersetLocale('en-US', 'en');
3060
+ * // Returns: false
3061
+ */
3062
+ isSupersetLocale(superLocale, subLocale) {
3063
+ return this.localeConfig.isSupersetLocale(superLocale, subLocale);
3064
+ }
3065
+ };
3066
+ /**
3067
+ * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.
3068
+ *
3069
+ * This standalone function provides cutoff formatting functionality without requiring a GT instance.
3070
+ * The locales parameter is required for proper terminator selection based on the target language.
3071
+ *
3072
+ * @param {string} value - The string value to format with cutoff behavior.
3073
+ * @param {Object} [options] - Configuration options for cutoff formatting.
3074
+ * @param {string | string[]} [options.locales] - The locales to use for terminator selection.
3075
+ * @param {number} [options.maxChars] - The maximum number of characters to display.
3076
+ * - Undefined values are treated as no cutoff.
3077
+ * - Negative values follow .slice() behavior and terminator will be added before the value.
3078
+ * - 0 will result in an empty string.
3079
+ * - If cutoff results in an empty string, no terminator is added.
3080
+ * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.
3081
+ * @param {string} [options.terminator] - Optional override the terminator to use.
3082
+ * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.
3083
+ * - If no terminator is provided, then separator is ignored.
3084
+ * @returns {string} The formatted string with terminator applied if cutoff occurs.
3085
+ *
3086
+ * @example
3087
+ * formatCutoff('Hello, world!', { locales: 'en-US', maxChars: 8 });
3088
+ * // Returns: 'Hello, w...'
3089
+ *
3090
+ * @example
3091
+ * formatCutoff('Hello, world!', { locales: 'en-US', maxChars: -3 });
3092
+ * // Returns: '...ld!'
3093
+ *
3094
+ * @example
3095
+ * formatCutoff('Very long text that needs cutting', {
3096
+ * locales: 'en-US',
3097
+ * maxChars: 15,
3098
+ * style: 'ellipsis',
3099
+ * separator: ' '
3100
+ * });
3101
+ * // Returns: 'Very long text ...'
3102
+ */
3103
+ function formatCutoff(value, options) {
3104
+ return _formatCutoff({
3105
+ value,
3106
+ locales: options?.locales,
3107
+ options
3108
+ });
3109
+ }
3110
+ /**
3111
+ * Formats a message according to the specified locales and options.
3112
+ *
3113
+ * @param {string} message - The message to format.
3114
+ * @param {string | string[]} [locales='en'] - The locales to use for formatting.
3115
+ * @param {FormatVariables} [variables={}] - The variables to use for formatting.
3116
+ * @param {StringFormat} [dataFormat='ICU'] - The format of the message. (When STRING, the message is returned as is)
3117
+ * @returns {string} The formatted message.
3118
+ *
3119
+ * @example
3120
+ * formatMessage('Hello {name}', { name: 'John' });
3121
+ * // Returns: "Hello John"
3122
+ *
3123
+ * formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });
3124
+ * // Returns: "Bonjour John"
3125
+ */
3126
+ function formatMessage(message, options) {
3127
+ switch (options?.dataFormat) {
3128
+ case "STRING": return _formatMessageString(message);
3129
+ default: return _formatMessageICU(message, options?.locales, options?.variables);
3130
+ }
3131
+ }
3132
+ /**
3133
+ * Formats a number according to the specified locales and options.
3134
+ * @param {Object} params - The parameters for the number formatting.
3135
+ * @param {number} params.value - The number to format.
3136
+ * @param {Intl.NumberFormatOptions} [params.options] - Additional options for number formatting.
3137
+ * @param {string | string[]} [params.options.locales] - The locales to use for formatting.
3138
+ * @returns {string} The formatted number.
3139
+ */
3140
+ function formatNum(number, options) {
3141
+ return _formatNum({
3142
+ value: number,
3143
+ locales: options.locales,
3144
+ options
3145
+ });
3146
+ }
3147
+ /**
3148
+ * Formats a date according to the specified languages and options.
3149
+ * @param {Object} params - The parameters for the date formatting.
3150
+ * @param {Date} params.value - The date to format.
3151
+ * @param {Intl.DateTimeFormatOptions} [params.options] - Additional options for date formatting.
3152
+ * @param {string | string[]} [params.options.locales] - The languages to use for formatting.
3153
+ * @returns {string} The formatted date.
3154
+ */
3155
+ function formatDateTime(date, options) {
3156
+ return _formatDateTime({
3157
+ value: date,
3158
+ locales: options?.locales,
3159
+ options
3160
+ });
3161
+ }
3162
+ /**
3163
+ * Formats a currency value according to the specified languages, currency, and options.
3164
+ * @param {Object} params - The parameters for the currency formatting.
3165
+ * @param {number} params.value - The currency value to format.
3166
+ * @param {string} params.currency - The currency code (e.g., 'USD').
3167
+ * @param {Intl.NumberFormatOptions} [params.options={}] - Additional options for currency formatting.
3168
+ * @param {string | string[]} [params.options.locales] - The locale codes to use for formatting.
3169
+ * @returns {string} The formatted currency value.
3170
+ */
3171
+ function formatCurrency(value, currency, options) {
3172
+ return _formatCurrency({
3173
+ value,
3174
+ currency,
3175
+ locales: options.locales,
3176
+ options
3177
+ });
3178
+ }
3179
+ /**
3180
+ * Formats a list of items according to the specified locales and options.
3181
+ * @param {Object} params - The parameters for the list formatting.
3182
+ * @param {Array<string | number>} params.value - The list of items to format.
3183
+ * @param {Intl.ListFormatOptions} [params.options={}] - Additional options for list formatting.
3184
+ * @param {string | string[]} [params.options.locales] - The locales to use for formatting.
3185
+ * @returns {string} The formatted list.
3186
+ */
3187
+ function formatList(array, options) {
3188
+ return _formatList({
3189
+ value: array,
3190
+ locales: options.locales,
3191
+ options
3192
+ });
3193
+ }
3194
+ /**
3195
+ * Formats a list of items according to the specified locales and options.
3196
+ * @param {Array<T>} array - The list of items to format
3197
+ * @param {Object} [options] - Additional options for list formatting
3198
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
3199
+ * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options
3200
+ * @returns {Array<T | string>} The formatted list parts
3201
+ */
3202
+ function formatListToParts(array, options) {
3203
+ return _formatListToParts({
3204
+ value: array,
3205
+ locales: options?.locales,
3206
+ options
3207
+ });
3208
+ }
3209
+ /**
3210
+ * Formats a relative time value according to the specified locales and options.
3211
+ * @param {Object} params - The parameters for the relative time formatting.
3212
+ * @param {number} params.value - The relative time value to format.
3213
+ * @param {Intl.RelativeTimeFormatUnit} params.unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year').
3214
+ * @param {Intl.RelativeTimeFormatOptions} [params.options={}] - Additional options for relative time formatting.
3215
+ * @param {string | string[]} [params.options.locales] - The locales to use for formatting.
3216
+ * @returns {string} The formatted relative time string.
3217
+ */
3218
+ function formatRelativeTime(value, unit, options) {
3219
+ return _formatRelativeTime({
3220
+ value,
3221
+ unit,
3222
+ locales: options.locales,
3223
+ options
3224
+ });
3225
+ }
3226
+ /**
3227
+ * Formats a relative time string from a Date, automatically selecting the best unit.
3228
+ * @param {Date} date - The date to format relative to now.
3229
+ * @param {Object} options - Formatting options.
3230
+ * @param {string | string[]} options.locales - The locales to use for formatting.
3231
+ * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options.
3232
+ * @returns {string} The formatted relative time string (e.g., "2 hours ago", "in 3 days").
3233
+ */
3234
+ function formatRelativeTimeFromDate(date, options) {
3235
+ const { locales, baseDate, ...intlOptions } = options;
3236
+ return _formatRelativeTimeFromDate({
3237
+ date,
3238
+ baseDate: baseDate ?? /* @__PURE__ */ new Date(),
3239
+ locales,
3240
+ options: intlOptions
3241
+ });
3242
+ }
3243
+ /**
3244
+ * Retrieves the display name of locale code using Intl.DisplayNames.
3245
+ *
3246
+ * @param {string} locale - A BCP-47 locale code.
3247
+ * @param {string} [defaultLocale] - The default locale to use for formatting.
3248
+ * @param {CustomMapping} [customMapping] - A custom mapping of locale codes to their names.
3249
+ * @returns {string} The display name corresponding to the code.
3250
+ */
3251
+ function getLocaleName(locale, defaultLocale, customMapping) {
3252
+ return _getLocaleName(locale, defaultLocale, customMapping);
3253
+ }
3254
+ /**
3255
+ * Retrieves an emoji based on a given locale code, taking into account region, language, and specific exceptions.
3256
+ *
3257
+ * This function uses the locale's region (if present) to select an emoji or falls back on default emojis for certain languages.
3258
+ *
3259
+ * @param locale - A string representing the locale code (e.g., 'en-US', 'fr-CA').
3260
+ * @param {CustomMapping} [customMapping] - A custom mapping of locale codes to their names.
3261
+ * @returns The emoji representing the locale or its region, or a default emoji if no specific match is found.
3262
+ */
3263
+ function getLocaleEmoji(locale, customMapping) {
3264
+ return _getLocaleEmoji(locale, customMapping);
3265
+ }
3266
+ /**
3267
+ * Generates linguistic details for a given locale code.
3268
+ *
3269
+ * This function returns information about the locale,
3270
+ * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).
3271
+ * The function provides these names in both your default language and native forms, and an associated emoji.
3272
+ *
3273
+ * @param {string} locale - The locale code to get properties for (e.g., "de-AT").
3274
+ * @param {string} [defaultLocale] - The default locale to use for formatting.
3275
+ * @param {CustomMapping} [customMapping] - A custom mapping of locale codes to their names.
3276
+ * @returns {LocaleProperties} - An object containing detailed information about the locale.
3277
+ *
3278
+ * @property {string} code - The full locale code, e.g., "de-AT".
3279
+ * @property {string} name - Language name in the default display language, e.g., "Austrian German".
3280
+ * @property {string} nativeName - Language name in the locale's native language, e.g., "Österreichisches Deutsch".
3281
+ * @property {string} languageCode - The base language code, e.g., "de".
3282
+ * @property {string} languageName - The language name in the default display language, e.g., "German".
3283
+ * @property {string} nativeLanguageName - The language name in the native language, e.g., "Deutsch".
3284
+ * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., "German (AT)".
3285
+ * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., "Deutsch (AT)".
3286
+ * @property {string} regionCode - The region code from maximization, e.g., "AT".
3287
+ * @property {string} regionName - The region name in the default display language, e.g., "Austria".
3288
+ * @property {string} nativeRegionName - The region name in the native language, e.g., "Österreich".
3289
+ * @property {string} scriptCode - The script code from maximization, e.g., "Latn".
3290
+ * @property {string} scriptName - The script name in the default display language, e.g., "Latin".
3291
+ * @property {string} nativeScriptName - The script name in the native language, e.g., "Lateinisch".
3292
+ * @property {string} maximizedCode - The maximized locale code, e.g., "de-Latn-AT".
3293
+ * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., "Austrian German (Latin)".
3294
+ * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., "Österreichisches Deutsch (Lateinisch)".
3295
+ * @property {string} minimizedCode - Minimized locale code, e.g., "de-AT" (or "de" for "de-DE").
3296
+ * @property {string} minimizedName - Minimized language name in the default language, e.g., "Austrian German".
3297
+ * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., "Österreichisches Deutsch".
3298
+ * @property {string} emoji - The emoji associated with the locale's region, if applicable.
3299
+ */
3300
+ function getLocaleProperties(locale, defaultLocale, customMapping) {
3301
+ return _getLocaleProperties(locale, defaultLocale, customMapping);
3302
+ }
3303
+ /**
3304
+ * Retrieves multiple properties for a given region code, including:
3305
+ * - `code`: the original region code
3306
+ * - `name`: the localized display name
3307
+ * - `emoji`: the associated flag or symbol
3308
+ *
3309
+ * Behavior:
3310
+ * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
3311
+ * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
3312
+ * - Otherwise, uses `Intl.DisplayNames` to get the localized region name in the given `defaultLocale`,
3313
+ * falling back to `libraryDefaultLocale`.
3314
+ * - Falls back to the region code as `name` if display name resolution fails.
3315
+ * - Falls back to `defaultEmoji` if no emoji mapping is found in `emojis` or `customMapping`.
3316
+ *
3317
+ * @param {string} region - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
3318
+ * @param {string} [defaultLocale=libraryDefaultLocale] - The locale to use when localizing the region name.
3319
+ * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
3320
+ * @returns {{ code: string, name: string, emoji: string }} An object containing:
3321
+ * - `code`: the input region code
3322
+ * - `name`: the localized or custom region name
3323
+ * - `emoji`: the matching emoji flag or symbol
3324
+ *
3325
+ * @example
3326
+ * getRegionProperties('US', 'en');
3327
+ * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
3328
+ *
3329
+ * @example
3330
+ * getRegionProperties('US', 'fr');
3331
+ * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
3332
+ *
3333
+ * @example
3334
+ * getRegionProperties('US', 'en', { US: { name: 'USA', emoji: '🗽' } });
3335
+ * // => { code: 'US', name: 'USA', emoji: '🗽' }
3336
+ */
3337
+ function getRegionProperties(region, defaultLocale, customMapping) {
3338
+ return _getRegionProperties(region, defaultLocale, customMapping);
3339
+ }
3340
+ /**
3341
+ * Determines whether a translation is required based on the source and target locales.
3342
+ *
3343
+ * - If the target locale is not specified, the function returns `false`, as translation is not needed.
3344
+ * - If the source and target locale are the same, returns `false`, indicating that no translation is necessary.
3345
+ * - If the `approvedLocales` array is provided, and the target locale is not within that array, the function also returns `false`.
3346
+ * - Otherwise, it returns `true`, meaning that a translation is required.
3347
+ *
3348
+ * @param {string} sourceLocale - The locale code for the original content (BCP 47 locale code).
3349
+ * @param {string} targetLocale - The locale code of the language to translate the content into (BCP 47 locale code).
3350
+ * @param {string[]} [approvedLocale] - An optional array of approved target locales.
3351
+ *
3352
+ * @returns {boolean} - Returns `true` if translation is required, otherwise `false`.
3353
+ */
3354
+ function requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping) {
3355
+ return _requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping);
3356
+ }
3357
+ /**
3358
+ * Determines the best matching locale from the provided approved locales list.
3359
+ * @param {string | string[]} locales - A single locale or an array of locales sorted in preference order.
3360
+ * @param {string[]} [approvedLocales=this.locales] - An array of approved locales, also sorted by preference.
3361
+ * @returns {string | undefined} - The best matching locale from the approvedLocales list, or undefined if no match is found.
3362
+ */
3363
+ function determineLocale(locales, approvedLocales = [], customMapping = void 0) {
3364
+ return _determineLocale(locales, approvedLocales, customMapping);
3365
+ }
3366
+ /**
3367
+ * Get the text direction for a given locale code using the Intl.Locale API.
3368
+ *
3369
+ * @param {string} locale - A BCP-47 locale code.
3370
+ * @returns {string} - 'rtl' if the locale is right-to-left, otherwise 'ltr'.
3371
+ */
3372
+ function getLocaleDirection(locale) {
3373
+ return _getLocaleDirection(locale);
3374
+ }
3375
+ /**
3376
+ * Checks if a given BCP 47 locale code is valid.
3377
+ * @param {string} locale - The BCP 47 locale code to validate.
3378
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for validation.
3379
+ * @returns {boolean} True if the BCP 47 code is valid, false otherwise.
3380
+ */
3381
+ function isValidLocale(locale, customMapping) {
3382
+ return _isValidLocale(locale, customMapping);
3383
+ }
3384
+ /**
3385
+ * Resolves the alias locale for a given locale.
3386
+ * @param {string} locale - The locale to resolve the alias locale for
3387
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for resolving the alias locale
3388
+ * @returns {string} The alias locale
3389
+ */
3390
+ function resolveAliasLocale(locale, customMapping) {
3391
+ return _resolveAliasLocale(locale, customMapping);
3392
+ }
3393
+ /**
3394
+ * Resolves the canonical locale for a given locale.
3395
+ * @param {string} locale - The locale to resolve the canonical locale for
3396
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for resolving the canonical locale
3397
+ * @returns {string} The canonical locale
3398
+ */
3399
+ function resolveCanonicalLocale(locale, customMapping) {
3400
+ return _resolveCanonicalLocale(locale, customMapping);
3401
+ }
3402
+ /**
3403
+ * Standardizes a BCP 47 locale code to ensure correct formatting.
3404
+ * @param {string} locale - The BCP 47 locale code to standardize.
3405
+ * @returns {string} The standardized BCP 47 locale code or an empty string if it is an invalid code.
3406
+ */
3407
+ function standardizeLocale(locale) {
3408
+ return _standardizeLocale(locale);
3409
+ }
3410
+ /**
3411
+ * Checks if multiple BCP 47 locale codes represent the same dialect.
3412
+ * @param {string[]} locales - The BCP 47 locale codes to compare.
3413
+ * @returns {boolean} True if all BCP 47 codes represent the same dialect, false otherwise.
3414
+ */
3415
+ function isSameDialect(...locales) {
3416
+ return _isSameDialect(...locales);
3417
+ }
3418
+ /**
3419
+ * Checks if multiple BCP 47 locale codes represent the same language.
3420
+ * @param {string[]} locales - The BCP 47 locale codes to compare.
3421
+ * @returns {boolean} True if all BCP 47 codes represent the same language, false otherwise.
3422
+ */
3423
+ function isSameLanguage(...locales) {
3424
+ return _isSameLanguage(...locales);
3425
+ }
3426
+ /**
3427
+ * Checks if a locale is a superset of another locale.
3428
+ * A subLocale is a subset of superLocale if it is an extension of superLocale or are otherwise identical.
3429
+ *
3430
+ * @param {string} superLocale - The locale to check if it is a superset of the other locale.
3431
+ * @param {string} subLocale - The locale to check if it is a subset of the other locale.
3432
+ * @returns {boolean} True if the first locale is a superset of the second locale, false otherwise.
3433
+ */
3434
+ function isSupersetLocale(superLocale, subLocale) {
3435
+ return _isSupersetLocale(superLocale, subLocale);
3436
+ }
3437
+ const API_VERSION = API_VERSION$1;
3438
+ //#endregion
3439
+ export { API_VERSION, GT, LocaleConfig, determineLocale, formatCurrency, formatCutoff, formatDateTime, formatList, formatListToParts, formatMessage, formatNum, formatRelativeTime, formatRelativeTimeFromDate, getLocaleDirection, getLocaleEmoji, getLocaleName, getLocaleProperties, getRegionProperties, isSameDialect, isSameLanguage, isSupersetLocale, isValidLocale, requiresTranslation, resolveAliasLocale, resolveCanonicalLocale, standardizeLocale };
3440
+
3441
+ //# sourceMappingURL=index.mjs.map