generaltranslation 8.2.6 → 8.2.7

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 +8 -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 +3354 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +1157 -0
  21. package/dist/index.d.mts +1157 -0
  22. package/dist/index.mjs +3305 -0
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/internal-CTeI8uLd.mjs +774 -0
  25. package/dist/internal-CTeI8uLd.mjs.map +1 -0
  26. package/dist/internal-PCKq4YMW.cjs +1012 -0
  27. package/dist/internal-PCKq4YMW.cjs.map +1 -0
  28. package/dist/internal.cjs +43 -0
  29. package/dist/{internal.d.ts → internal.d.cts} +62 -114
  30. package/dist/internal.d.mts +242 -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-D2fTTTvZ.d.cts +737 -0
  37. package/dist/types-fUW4_Ole.d.mts +737 -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,3305 @@
1
+ import { A as encode, R as intlCache, k as decode, z as defaultTimeout } from "./internal-CTeI8uLd.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
+ const result = await processBatches(files, async (batch) => {
1449
+ const apiResult = await apiRequest(config, "/v2/project/translations/enqueue", {
1450
+ body: {
1451
+ files: batch.map((f) => ({
1452
+ branchId: f.branchId,
1453
+ fileId: f.fileId,
1454
+ versionId: f.versionId,
1455
+ fileName: f.fileName
1456
+ })),
1457
+ targetLocales: options.targetLocales,
1458
+ sourceLocale: options.sourceLocale,
1459
+ requireApproval: options.requireApproval,
1460
+ modelProvider: options.modelProvider,
1461
+ force: options.force
1462
+ },
1463
+ timeout: options.timeout
1464
+ });
1465
+ return Array.from(Object.entries(apiResult.jobData));
1466
+ }, { batchSize: 100 });
1467
+ return {
1468
+ jobData: Object.fromEntries(result.data.map(([jobId, jobData]) => [jobId, jobData])),
1469
+ locales: options.targetLocales,
1470
+ message: `Successfully enqueued ${result.count} file translation jobs in ${result.batchCount} batch(es)`
1471
+ };
1472
+ }
1473
+ //#endregion
1474
+ //#region src/translate/createTag.ts
1475
+ /**
1476
+ * @internal
1477
+ * Creates or upserts a file tag in the General Translation API.
1478
+ * @param options - The tag creation options
1479
+ * @param config - The configuration for the API call
1480
+ * @returns The created or updated tag
1481
+ */
1482
+ async function _createTag(options, config) {
1483
+ return await apiRequest(config, "/v2/project/tags/create", { body: {
1484
+ tagId: options.tagId,
1485
+ files: options.files,
1486
+ ...options.message && { message: options.message }
1487
+ } });
1488
+ }
1489
+ //#endregion
1490
+ //#region src/translate/downloadFileBatch.ts
1491
+ /**
1492
+ * @internal
1493
+ * Downloads multiple translation files in batches.
1494
+ * @param files - Array of files to download
1495
+ * @param options - The options for the API call
1496
+ * @param config - The configuration for the request
1497
+ * @returns Promise resolving to a BatchList with all downloaded files
1498
+ */
1499
+ async function _downloadFileBatch(requests, options, config) {
1500
+ return processBatches(requests, async (batch) => {
1501
+ return (await apiRequest(config, "/v2/project/files/download", {
1502
+ body: batch,
1503
+ timeout: options.timeout
1504
+ })).files.map((file) => ({
1505
+ ...file,
1506
+ data: decode(file.data)
1507
+ }));
1508
+ }, { batchSize: 100 });
1509
+ }
1510
+ //#endregion
1511
+ //#region src/translate/submitUserEditDiffs.ts
1512
+ /**
1513
+ * @internal
1514
+ * Submits user edit diffs so the service can learn/persist user-intended rules.
1515
+ */
1516
+ async function _submitUserEditDiffs(payload, config, options = {}) {
1517
+ await processBatches(payload.diffs, async (batch) => {
1518
+ await apiRequest(config, "/v2/project/files/diffs", {
1519
+ body: { diffs: batch },
1520
+ timeout: options.timeout
1521
+ });
1522
+ return [{ success: true }];
1523
+ }, { batchSize: 100 });
1524
+ return { success: true };
1525
+ }
1526
+ //#endregion
1527
+ //#region src/locales/getRegionProperties.ts
1528
+ /**
1529
+ * Retrieves multiple properties for a given region code, including:
1530
+ * - `code`: the original region code
1531
+ * - `name`: the localized display name
1532
+ * - `emoji`: the associated flag or symbol
1533
+ *
1534
+ * Behavior:
1535
+ * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
1536
+ * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
1537
+ * - Otherwise, uses `Intl.DisplayNames` to get the localized region name in the given `defaultLocale`,
1538
+ * falling back to `libraryDefaultLocale`.
1539
+ * - Falls back to the region code as `name` if display name resolution fails.
1540
+ * - Falls back to `defaultEmoji` if no emoji mapping is found in `emojis` or `customMapping`.
1541
+ *
1542
+ * @param {string} region - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
1543
+ * @param {string} [defaultLocale=libraryDefaultLocale] - The locale to use when localizing the region name.
1544
+ * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
1545
+ * @returns {{ code: string, name: string, emoji: string }} An object containing:
1546
+ * - `code`: the input region code
1547
+ * - `name`: the localized or custom region name
1548
+ * - `emoji`: the matching emoji flag or symbol
1549
+ * @internal
1550
+ *
1551
+ * @example
1552
+ * _getRegionProperties('US', 'en');
1553
+ * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
1554
+ *
1555
+ * @example
1556
+ * _getRegionProperties('US', 'fr');
1557
+ * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
1558
+ *
1559
+ * @example
1560
+ * _getRegionProperties('US', 'en', { US: { name: 'USA', emoji: '🗽' } });
1561
+ * // => { code: 'US', name: 'USA', emoji: '🗽' }
1562
+ */
1563
+ function _getRegionProperties(region, defaultLocale = "en", customMapping) {
1564
+ defaultLocale ||= "en";
1565
+ try {
1566
+ return {
1567
+ code: region,
1568
+ name: intlCache.get("DisplayNames", [defaultLocale, "en"], { type: "region" }).of(region) || region,
1569
+ emoji: emojis[region] || "🌍",
1570
+ ...customMapping?.[region]
1571
+ };
1572
+ } catch {
1573
+ return {
1574
+ code: region,
1575
+ name: region,
1576
+ emoji: defaultEmoji,
1577
+ ...customMapping?.[region]
1578
+ };
1579
+ }
1580
+ }
1581
+ //#endregion
1582
+ //#region src/locales/resolveAliasLocale.ts
1583
+ /**
1584
+ * Resolves the alias locale for a given locale.
1585
+ * @param locale - The locale to resolve the alias locale for
1586
+ * @param customMapping - The custom mapping to use for resolving the alias locale
1587
+ * @returns The alias locale
1588
+ */
1589
+ function _resolveAliasLocale(locale, customMapping) {
1590
+ let reverseCustomMapping;
1591
+ if (customMapping) reverseCustomMapping = Object.fromEntries(Object.entries(customMapping).filter(([, value]) => value && typeof value === "object" && "code" in value).map(([key, value]) => [value.code, key]));
1592
+ return reverseCustomMapping?.[locale] || locale;
1593
+ }
1594
+ //#endregion
1595
+ //#region src/locales/resolveCanonicalLocale.ts
1596
+ /**
1597
+ * Resolves the canonical locale for a given locale.
1598
+ * @param locale - The locale to resolve the canonical locale for
1599
+ * @param customMapping - The custom mapping to use for resolving the canonical locale
1600
+ * @returns The canonical locale
1601
+ */
1602
+ function _resolveCanonicalLocale(locale, customMapping) {
1603
+ if (customMapping && shouldUseCanonicalLocale(locale, customMapping)) return customMapping[locale].code;
1604
+ return locale;
1605
+ }
1606
+ //#endregion
1607
+ //#region src/translate/uploadSourceFiles.ts
1608
+ /**
1609
+ * @internal
1610
+ * Uploads source files to the General Translation API in batches.
1611
+ * @param files - The files to upload
1612
+ * @param options - The options for the API call
1613
+ * @param config - The configuration for the API call
1614
+ * @returns Promise resolving to a BatchList with all uploaded files
1615
+ */
1616
+ async function _uploadSourceFiles(files, options, config) {
1617
+ return processBatches(files, async (batch) => {
1618
+ return (await apiRequest(config, "/v2/project/files/upload-files", {
1619
+ body: {
1620
+ data: batch.map(({ source }) => ({ source: {
1621
+ content: encode(source.content),
1622
+ fileName: source.fileName,
1623
+ fileFormat: source.fileFormat,
1624
+ locale: source.locale,
1625
+ dataFormat: source.dataFormat,
1626
+ formatMetadata: source.formatMetadata,
1627
+ fileId: source.fileId,
1628
+ versionId: source.versionId,
1629
+ branchId: source.branchId,
1630
+ incomingBranchId: source.incomingBranchId,
1631
+ checkedOutBranchId: source.checkedOutBranchId
1632
+ } })),
1633
+ sourceLocale: options.sourceLocale
1634
+ },
1635
+ timeout: options.timeout
1636
+ })).uploadedFiles || [];
1637
+ }, { batchSize: 100 });
1638
+ }
1639
+ //#endregion
1640
+ //#region src/translate/uploadTranslations.ts
1641
+ /**
1642
+ * @internal
1643
+ * Uploads multiple translations to the General Translation API in batches.
1644
+ * @param files - Translations to upload with their source
1645
+ * @param options - The options for the API call
1646
+ * @param config - The configuration for the API call
1647
+ * @returns Promise resolving to a BatchList with all uploaded files
1648
+ */
1649
+ async function _uploadTranslations(files, options, config) {
1650
+ return processBatches(files, async (batch) => {
1651
+ return (await apiRequest(config, "/v2/project/files/upload-translations", {
1652
+ body: {
1653
+ data: batch.map(({ source, translations }) => ({
1654
+ source: {
1655
+ content: encode(source.content),
1656
+ fileName: source.fileName,
1657
+ fileFormat: source.fileFormat,
1658
+ locale: source.locale,
1659
+ dataFormat: source.dataFormat,
1660
+ formatMetadata: source.formatMetadata,
1661
+ fileId: source.fileId,
1662
+ versionId: source.versionId,
1663
+ branchId: source.branchId
1664
+ },
1665
+ translations: translations.map((t) => ({
1666
+ content: encode(t.content),
1667
+ fileName: t.fileName,
1668
+ fileFormat: t.fileFormat,
1669
+ locale: t.locale,
1670
+ dataFormat: t.dataFormat,
1671
+ fileId: t.fileId,
1672
+ versionId: t.versionId,
1673
+ branchId: t.branchId
1674
+ }))
1675
+ })),
1676
+ sourceLocale: options.sourceLocale
1677
+ },
1678
+ timeout: options.timeout
1679
+ })).uploadedFiles || [];
1680
+ }, { batchSize: 100 });
1681
+ }
1682
+ //#endregion
1683
+ //#region src/translate/querySourceFile.ts
1684
+ /**
1685
+ * @internal
1686
+ * Gets the source file and translation information for a given file ID and version ID.
1687
+ * @param query - The file ID and version ID to get the source file and translation information for
1688
+ * @param options - The options for the API call
1689
+ * @param config - The configuration for the request
1690
+ * @returns The source file and translation information for the given file ID and version ID
1691
+ */
1692
+ async function _querySourceFile(query, options, config) {
1693
+ const branchId = query.branchId;
1694
+ const versionId = query.versionId;
1695
+ const fileId = query.fileId;
1696
+ const searchParams = new URLSearchParams();
1697
+ if (branchId) searchParams.set("branchId", branchId);
1698
+ if (versionId) searchParams.set("versionId", versionId);
1699
+ return apiRequest(config, `/v2/project/translations/files/status/${encodeURIComponent(fileId)}?${searchParams.toString()}`, {
1700
+ method: "GET",
1701
+ timeout: options.timeout
1702
+ });
1703
+ }
1704
+ //#endregion
1705
+ //#region src/projects/getProjectData.ts
1706
+ /**
1707
+ * @internal
1708
+ * Gets the project data for a given project ID.
1709
+ * @param projectId - The project ID to get the project data for
1710
+ * @param options - The options for the API call
1711
+ * @param config - The configuration for the request
1712
+ * @returns The project data for the given project ID
1713
+ */
1714
+ async function _getProjectData(projectId, options, config) {
1715
+ const { baseUrl } = config;
1716
+ const timeout = options.timeout ? options.timeout : defaultTimeout;
1717
+ const url = `${baseUrl || "https://api2.gtx.dev"}/v2/project/info/${encodeURIComponent(projectId)}`;
1718
+ let response;
1719
+ try {
1720
+ response = await fetchWithTimeout(url, {
1721
+ method: "GET",
1722
+ headers: generateRequestHeaders(config)
1723
+ }, timeout);
1724
+ } catch (error) {
1725
+ handleFetchError(error, timeout);
1726
+ }
1727
+ await validateResponse(response);
1728
+ return await response.json();
1729
+ }
1730
+ //#endregion
1731
+ //#region src/translate/checkJobStatus.ts
1732
+ /**
1733
+ * @internal
1734
+ * Queries job statuses for a project
1735
+ * @param jobIds - Job IDs
1736
+ * @param config - The configuration for the API call
1737
+ * @param timeoutMS - The timeout in milliseconds
1738
+ * @returns The result of the API call
1739
+ */
1740
+ async function _checkJobStatus(jobIds, config, timeoutMs) {
1741
+ return apiRequest(config, "/v2/project/jobs/info", {
1742
+ body: { jobIds },
1743
+ timeout: timeoutMs
1744
+ });
1745
+ }
1746
+ //#endregion
1747
+ //#region src/translate/awaitJobs.ts
1748
+ /**
1749
+ * @internal
1750
+ * Polls job statuses until all jobs are finished or the timeout is reached.
1751
+ * @param enqueueResult - The result from enqueueFiles
1752
+ * @param options - Polling configuration
1753
+ * @param config - API credentials and configuration
1754
+ * @returns The final status of all jobs
1755
+ */
1756
+ async function _awaitJobs(enqueueResult, options, config) {
1757
+ const pollingInterval = (options?.pollingIntervalSeconds ?? 5) * 1e3;
1758
+ const timeout = options?.timeoutSeconds !== void 0 ? options.timeoutSeconds * 1e3 : 600 * 1e3;
1759
+ const jobIds = Object.keys(enqueueResult.jobData);
1760
+ if (jobIds.length === 0) return {
1761
+ complete: true,
1762
+ jobs: []
1763
+ };
1764
+ const startTime = Date.now();
1765
+ const finalStatuses = new Map(jobIds.map((id) => [id, {
1766
+ jobId: id,
1767
+ status: "unknown"
1768
+ }]));
1769
+ const pendingJobIds = new Set(jobIds);
1770
+ while (pendingJobIds.size > 0) {
1771
+ const statuses = await _checkJobStatus(Array.from(pendingJobIds), config);
1772
+ for (const job of statuses) if (job.status === "completed" || job.status === "failed" || job.status === "unknown") {
1773
+ finalStatuses.set(job.jobId, {
1774
+ jobId: job.jobId,
1775
+ status: job.status,
1776
+ ...job.error ? { error: job.error } : {}
1777
+ });
1778
+ pendingJobIds.delete(job.jobId);
1779
+ } else finalStatuses.set(job.jobId, {
1780
+ jobId: job.jobId,
1781
+ status: job.status
1782
+ });
1783
+ if (pendingJobIds.size === 0) break;
1784
+ if (Date.now() - startTime >= timeout) break;
1785
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
1786
+ }
1787
+ return {
1788
+ complete: pendingJobIds.size === 0,
1789
+ jobs: Array.from(finalStatuses.values())
1790
+ };
1791
+ }
1792
+ //#endregion
1793
+ //#region src/translate/queryFileData.ts
1794
+ /**
1795
+ * @internal
1796
+ * Queries data about one or more source or translation files.
1797
+ * @param data - Object mapping source or translation file information
1798
+ * @param options - The options for the API call
1799
+ * @param config - The configuration for the API call
1800
+ * @returns The file data
1801
+ */
1802
+ async function _queryFileData(data, options = {}, config) {
1803
+ return apiRequest(config, "/v2/project/files/info", {
1804
+ body: {
1805
+ sourceFiles: data.sourceFiles?.map((item) => ({
1806
+ fileId: item.fileId,
1807
+ versionId: item.versionId,
1808
+ branchId: item.branchId
1809
+ })),
1810
+ translatedFiles: data.translatedFiles?.map((item) => ({
1811
+ fileId: item.fileId,
1812
+ versionId: item.versionId,
1813
+ branchId: item.branchId,
1814
+ locale: item.locale
1815
+ }))
1816
+ },
1817
+ timeout: options.timeout
1818
+ });
1819
+ }
1820
+ //#endregion
1821
+ //#region src/translate/queryBranchData.ts
1822
+ /**
1823
+ * @internal
1824
+ * Queries branch information from the API.
1825
+ * @param query - Object mapping the current branch and incoming branches
1826
+ * @param config - The configuration for the API call
1827
+ * @returns The branch information
1828
+ */
1829
+ async function _queryBranchData(query, config) {
1830
+ return apiRequest(config, "/v2/project/branches/info", { body: query });
1831
+ }
1832
+ //#endregion
1833
+ //#region src/translate/createBranch.ts
1834
+ /**
1835
+ * @internal
1836
+ * Creates a new branch in the API.
1837
+ * @param query - Object mapping the branch name and default branch flag
1838
+ * @param config - The configuration for the API call
1839
+ * @returns The created branch information
1840
+ */
1841
+ async function _createBranch(query, config) {
1842
+ return apiRequest(config, "/v2/project/branches/create", { body: query });
1843
+ }
1844
+ //#endregion
1845
+ //#region src/translate/processFileMoves.ts
1846
+ /**
1847
+ * @internal
1848
+ * Processes file moves by cloning source files and translations with new fileIds.
1849
+ * Called when the CLI detects that files have been moved/renamed.
1850
+ * @param moves - Array of move mappings (old fileId to new fileId)
1851
+ * @param options - Options including branchId and timeout
1852
+ * @param config - The configuration for the API call
1853
+ * @returns Promise resolving to the move results
1854
+ */
1855
+ async function _processFileMoves(moves, options, config) {
1856
+ if (moves.length === 0) return {
1857
+ results: [],
1858
+ summary: {
1859
+ total: 0,
1860
+ succeeded: 0,
1861
+ failed: 0
1862
+ }
1863
+ };
1864
+ const batchResult = await processBatches(moves, async (batch) => {
1865
+ return (await apiRequest(config, "/v2/project/files/moves", {
1866
+ body: {
1867
+ branchId: options.branchId,
1868
+ moves: batch
1869
+ },
1870
+ timeout: options.timeout
1871
+ })).results;
1872
+ }, { batchSize: 100 });
1873
+ const succeeded = batchResult.data.filter((r) => r.success).length;
1874
+ const failed = batchResult.data.filter((r) => !r.success).length;
1875
+ return {
1876
+ results: batchResult.data,
1877
+ summary: {
1878
+ total: moves.length,
1879
+ succeeded,
1880
+ failed
1881
+ }
1882
+ };
1883
+ }
1884
+ //#endregion
1885
+ //#region src/translate/getOrphanedFiles.ts
1886
+ /**
1887
+ * @internal
1888
+ * Gets orphaned files for a branch - files that exist on the branch
1889
+ * but whose fileIds are not in the provided list.
1890
+ * Used for move detection.
1891
+ * @param branchId - The branch to check for orphaned files
1892
+ * @param fileIds - List of current file IDs (files that are NOT orphaned)
1893
+ * @param options - The options for the API call
1894
+ * @param config - The configuration for the API call
1895
+ * @returns The orphaned files
1896
+ */
1897
+ async function _getOrphanedFiles(branchId, fileIds, options = {}, config) {
1898
+ const makeRequest = (batchFileIds) => apiRequest(config, "/v2/project/files/orphaned", {
1899
+ body: {
1900
+ branchId,
1901
+ fileIds: batchFileIds
1902
+ },
1903
+ timeout: options.timeout
1904
+ });
1905
+ if (fileIds.length === 0) return makeRequest([]);
1906
+ const batches = createBatches(fileIds, 100);
1907
+ const batchResults = await Promise.all(batches.map((batch) => makeRequest(batch)));
1908
+ if (batchResults.length === 1) return batchResults[0];
1909
+ const orphanedFileMap = /* @__PURE__ */ new Map();
1910
+ for (const orphan of batchResults[0].orphanedFiles) orphanedFileMap.set(orphan.fileId, orphan);
1911
+ for (let i = 1; i < batchResults.length; i++) {
1912
+ const batchOrphanIds = new Set(batchResults[i].orphanedFiles.map((f) => f.fileId));
1913
+ Array.from(orphanedFileMap.keys()).forEach((fileId) => {
1914
+ if (!batchOrphanIds.has(fileId)) orphanedFileMap.delete(fileId);
1915
+ });
1916
+ }
1917
+ return { orphanedFiles: Array.from(orphanedFileMap.values()) };
1918
+ }
1919
+ //#endregion
1920
+ //#region src/translate/publishFiles.ts
1921
+ /**
1922
+ * @internal
1923
+ * Publishes or unpublishes files on the CDN.
1924
+ * @param files - Array of file entries with publish flags
1925
+ * @param config - The configuration for the API call
1926
+ * @returns The result of the API call
1927
+ */
1928
+ async function _publishFiles(files, config) {
1929
+ return await apiRequest(config, "/v2/project/files/publish", { body: { files } });
1930
+ }
1931
+ //#endregion
1932
+ //#region src/index.ts
1933
+ /**
1934
+ * GT is the core driver for the General Translation library.
1935
+ * This class provides functionality for locale management, formatting, and translation operations.
1936
+ *
1937
+ * @class GT
1938
+ * @description A comprehensive toolkit for handling internationalization and localization.
1939
+ *
1940
+ * @example
1941
+ * const gt = new GT({
1942
+ * sourceLocale: 'en-US',
1943
+ * targetLocale: 'es-ES',
1944
+ * locales: ['en-US', 'es-ES', 'fr-FR']
1945
+ * });
1946
+ */
1947
+ var GT = class {
1948
+ /**
1949
+ * Constructs an instance of the GT class.
1950
+ *
1951
+ * @param {GTConstructorParams} [params] - The parameters for initializing the GT instance
1952
+ * @throws {Error} If an invalid locale is provided
1953
+ * @throws {Error} If any of the provided locales are invalid
1954
+ *
1955
+ * @example
1956
+ * const gt = new GT({
1957
+ * apiKey: 'your-api-key',
1958
+ * sourceLocale: 'en-US',
1959
+ * targetLocale: 'es-ES',
1960
+ * locales: ['en-US', 'es-ES', 'fr-FR']
1961
+ * });
1962
+ */
1963
+ constructor(params = {}) {
1964
+ this._renderingLocales = [];
1965
+ if (typeof process !== "undefined") {
1966
+ this.apiKey ||= process.env?.GT_API_KEY;
1967
+ this.devApiKey ||= process.env?.GT_DEV_API_KEY;
1968
+ this.projectId ||= process.env?.GT_PROJECT_ID;
1969
+ }
1970
+ this.setConfig(params);
1971
+ }
1972
+ setConfig({ apiKey, devApiKey, sourceLocale, targetLocale, locales, projectId, customMapping, baseUrl }) {
1973
+ if (apiKey) this.apiKey = apiKey;
1974
+ if (devApiKey) this.devApiKey = devApiKey;
1975
+ if (projectId) this.projectId = projectId;
1976
+ if (sourceLocale) {
1977
+ this.sourceLocale = _standardizeLocale(sourceLocale);
1978
+ if (!_isValidLocale(this.sourceLocale, customMapping)) throw new Error(invalidLocaleError(this.sourceLocale));
1979
+ }
1980
+ if (targetLocale) {
1981
+ this.targetLocale = _standardizeLocale(targetLocale);
1982
+ if (!_isValidLocale(this.targetLocale, customMapping)) throw new Error(invalidLocaleError(this.targetLocale));
1983
+ }
1984
+ this._renderingLocales = [];
1985
+ if (this.sourceLocale) this._renderingLocales.push(this.sourceLocale);
1986
+ if (this.targetLocale) this._renderingLocales.push(this.targetLocale);
1987
+ this._renderingLocales.push("en");
1988
+ if (locales) {
1989
+ const result = [];
1990
+ const invalidLocales = [];
1991
+ locales.forEach((locale) => {
1992
+ const standardizedLocale = _standardizeLocale(locale);
1993
+ if (_isValidLocale(standardizedLocale)) result.push(standardizedLocale);
1994
+ else invalidLocales.push(locale);
1995
+ });
1996
+ if (invalidLocales.length > 0) throw new Error(invalidLocalesError(invalidLocales));
1997
+ this.locales = result;
1998
+ }
1999
+ if (baseUrl) this.baseUrl = baseUrl;
2000
+ if (customMapping) {
2001
+ this.customMapping = customMapping;
2002
+ this.reverseCustomMapping = Object.fromEntries(Object.entries(customMapping).filter(([, value]) => value && typeof value === "object" && "code" in value).map(([key, value]) => [value.code, key]));
2003
+ }
2004
+ }
2005
+ _getTranslationConfig() {
2006
+ return {
2007
+ baseUrl: this.baseUrl,
2008
+ apiKey: this.apiKey || this.devApiKey,
2009
+ projectId: this.projectId || ""
2010
+ };
2011
+ }
2012
+ _validateAuth(functionName) {
2013
+ const errors = [];
2014
+ if (!this.apiKey && !this.devApiKey) {
2015
+ const error = noApiKeyProvidedError(functionName);
2016
+ errors.push(error);
2017
+ }
2018
+ if (!this.projectId) {
2019
+ const error = noProjectIdProvidedError(functionName);
2020
+ errors.push(error);
2021
+ }
2022
+ if (errors.length) throw new Error(errors.join("\n"));
2023
+ }
2024
+ /**
2025
+ * Queries branch information from the API.
2026
+ *
2027
+ * @param {BranchQuery} query - Object mapping the current branch and incoming branches
2028
+ * @returns {Promise<BranchDataResult>} The branch information
2029
+ */
2030
+ async queryBranchData(query) {
2031
+ this._validateAuth("queryBranchData");
2032
+ return await _queryBranchData(query, this._getTranslationConfig());
2033
+ }
2034
+ /**
2035
+ * Creates a new branch in the API. If the branch already exists, it will be returned.
2036
+ *
2037
+ * @param {CreateBranchQuery} query - Object mapping the branch name and default branch flag
2038
+ * @returns {Promise<CreateBranchResult>} The created branch information
2039
+ */
2040
+ async createBranch(query) {
2041
+ this._validateAuth("createBranch");
2042
+ return await _createBranch(query, this._getTranslationConfig());
2043
+ }
2044
+ /**
2045
+ * Processes file moves by cloning source files and translations with new fileIds.
2046
+ * This is called when files have been moved/renamed and we want to preserve translations.
2047
+ *
2048
+ * @param {MoveMapping[]} moves - Array of move mappings (old fileId to new fileId)
2049
+ * @param {ProcessMovesOptions} options - Options including branchId and timeout
2050
+ * @returns {Promise<ProcessMovesResponse>} The move processing results
2051
+ *
2052
+ * @example
2053
+ * const result = await gt.processFileMoves([
2054
+ * { oldFileId: 'abc123', newFileId: 'def456', newFileName: 'locales/en.json' }
2055
+ * ], { branchId: 'main' });
2056
+ */
2057
+ async processFileMoves(moves, options = {}) {
2058
+ this._validateAuth("processFileMoves");
2059
+ return await _processFileMoves(moves, options, this._getTranslationConfig());
2060
+ }
2061
+ /**
2062
+ * Gets orphaned files for a branch - files that exist on the branch
2063
+ * but whose fileIds are not in the provided list.
2064
+ * Used for move detection.
2065
+ *
2066
+ * @param {string} branchId - The branch to check for orphaned files
2067
+ * @param {string[]} fileIds - List of current file IDs (files that are NOT orphaned)
2068
+ * @param {Object} options - Options including timeout
2069
+ * @returns {Promise<GetOrphanedFilesResult>} The orphaned files
2070
+ *
2071
+ * @example
2072
+ * const result = await gt.getOrphanedFiles('branch-id', ['file-1', 'file-2']);
2073
+ */
2074
+ async getOrphanedFiles(branchId, fileIds, options = {}) {
2075
+ this._validateAuth("getOrphanedFiles");
2076
+ return await _getOrphanedFiles(branchId, fileIds, options, this._getTranslationConfig());
2077
+ }
2078
+ /**
2079
+ * Enqueues project setup job using the specified file references
2080
+ *
2081
+ * This method creates setup jobs that will process source file references
2082
+ * and generate a project setup. The files parameter contains references (IDs) to source
2083
+ * files that have already been uploaded via uploadSourceFiles. The setup jobs are queued
2084
+ * for processing and will generate a project setup based on the source files.
2085
+ *
2086
+ * @param {FileReference[]} files - Array of file references containing IDs of previously uploaded source files
2087
+ * @param {SetupProjectOptions} [options] - Optional settings for target locales and timeout
2088
+ * @returns {Promise<SetupProjectResult>} Object containing the jobId and status
2089
+ */
2090
+ async setupProject(files, options) {
2091
+ this._validateAuth("setupProject");
2092
+ options = {
2093
+ ...options,
2094
+ locales: options?.locales?.map((locale) => this.resolveCanonicalLocale(locale))
2095
+ };
2096
+ return await _setupProject(files, this._getTranslationConfig(), options);
2097
+ }
2098
+ /**
2099
+ * Checks the current status of one or more project jobs by their unique identifiers.
2100
+ *
2101
+ * This method polls the API to determine whether one or more jobs are still running,
2102
+ * have completed successfully, or have failed. Jobs are created after calling either enqueueFiles or setupProject.
2103
+ *
2104
+ * @param {string[]} jobIds - The unique identifiers of the jobs to check
2105
+ * @param {number} [timeoutMs] - Optional timeout in milliseconds for the API request
2106
+ * @returns {Promise<CheckJobStatusResult>} Object containing the job status
2107
+ *
2108
+ * @example
2109
+ * const result = await gt.checkJobStatus([
2110
+ * 'job-123',
2111
+ * 'job-456',
2112
+ * ], {
2113
+ * timeout: 10000,
2114
+ * });
2115
+ */
2116
+ async checkJobStatus(jobIds, timeoutMs) {
2117
+ this._validateAuth("checkJobStatus");
2118
+ return await _checkJobStatus(jobIds, this._getTranslationConfig(), timeoutMs);
2119
+ }
2120
+ /**
2121
+ * Polls job statuses until all jobs from enqueueFiles are finished or the timeout is reached.
2122
+ *
2123
+ * @param {EnqueueFilesResult} enqueueResult - The result returned from enqueueFiles
2124
+ * @param {AwaitJobsOptions} [options] - Polling configuration (interval, timeout)
2125
+ * @returns {Promise<AwaitJobsResult>} The final status of all jobs and whether they all completed
2126
+ */
2127
+ async awaitJobs(enqueueResult, options) {
2128
+ this._validateAuth("awaitJobs");
2129
+ return await _awaitJobs(enqueueResult, options, this._getTranslationConfig());
2130
+ }
2131
+ /**
2132
+ * Enqueues translation jobs for previously uploaded source files.
2133
+ *
2134
+ * This method creates translation jobs that will process existing source files
2135
+ * and generate translations in the specified target languages. The files parameter
2136
+ * contains references (IDs) to source files that have already been uploaded via
2137
+ * uploadSourceFiles. The translation jobs are queued for processing and will
2138
+ * generate translated content based on the source files and target locales provided.
2139
+ *
2140
+ * @param {FileReferenceIds[]} files - Array of file references containing IDs of previously uploaded source files
2141
+ * @param {EnqueueOptions} options - Configuration options including source locale, target locales, and job settings
2142
+ * @returns {Promise<EnqueueFilesResult>} Result containing job IDs, queue status, and processing information
2143
+ */
2144
+ async enqueueFiles(files, options) {
2145
+ this._validateAuth("enqueueFiles");
2146
+ let mergedOptions = {
2147
+ ...options,
2148
+ sourceLocale: options.sourceLocale ?? this.sourceLocale,
2149
+ targetLocales: options.targetLocales ?? [this.targetLocale]
2150
+ };
2151
+ if (!mergedOptions.sourceLocale) {
2152
+ const error = noSourceLocaleProvidedError("enqueueFiles");
2153
+ gtInstanceLogger.error(error);
2154
+ throw new Error(error);
2155
+ }
2156
+ if (!mergedOptions.targetLocales || mergedOptions.targetLocales.length === 0) {
2157
+ const error = noTargetLocaleProvidedError("enqueueFiles");
2158
+ gtInstanceLogger.error(error);
2159
+ throw new Error(error);
2160
+ }
2161
+ mergedOptions = {
2162
+ ...mergedOptions,
2163
+ targetLocales: mergedOptions.targetLocales.map((locale) => this.resolveCanonicalLocale(locale))
2164
+ };
2165
+ return await _enqueueFiles(files, mergedOptions, this._getTranslationConfig());
2166
+ }
2167
+ /**
2168
+ * Creates or upserts a file tag, associating a set of source files
2169
+ * with a user-defined tag ID and optional message.
2170
+ *
2171
+ * @param {CreateTagOptions} options - Tag creation options including tagId, sourceFileIds, and optional message
2172
+ * @returns {Promise<CreateTagResult>} The created or updated tag
2173
+ */
2174
+ async createTag(options) {
2175
+ this._validateAuth("createTag");
2176
+ return await _createTag(options, this._getTranslationConfig());
2177
+ }
2178
+ /**
2179
+ * Publishes or unpublishes files on the CDN.
2180
+ *
2181
+ * @param {PublishFileEntry[]} files - Array of file entries with publish flags
2182
+ * @returns {Promise<PublishFilesResult>} Result containing per-file success/failure
2183
+ */
2184
+ async publishFiles(files) {
2185
+ this._validateAuth("publishFiles");
2186
+ return await _publishFiles(files, this._getTranslationConfig());
2187
+ }
2188
+ /**
2189
+ * Submits user edit diffs for existing translations so future generations preserve user intent.
2190
+ *
2191
+ * @param {SubmitUserEditDiffsPayload} payload - Project-scoped diff payload.
2192
+ * @returns {Promise<void>} Resolves when submission succeeds.
2193
+ */
2194
+ async submitUserEditDiffs(payload) {
2195
+ this._validateAuth("submitUserEditDiffs");
2196
+ await _submitUserEditDiffs({
2197
+ ...payload,
2198
+ diffs: (payload.diffs || []).map((d) => ({
2199
+ ...d,
2200
+ locale: this.resolveCanonicalLocale(d.locale)
2201
+ }))
2202
+ }, this._getTranslationConfig());
2203
+ }
2204
+ /**
2205
+ * Queries data about one or more source or translation files.
2206
+ *
2207
+ * @param {FileDataQuery} data - Object mapping source and translation file information.
2208
+ * @param {CheckFileTranslationsOptions} options - Options for the API call.
2209
+ * @returns {Promise<FileDataResult>} The source and translation file data information.
2210
+ *
2211
+ * @example
2212
+ * const result = await gt.queryFileData({
2213
+ * sourceFiles: [
2214
+ * { fileId: '1234567890', versionId: '1234567890', branchId: '1234567890' },
2215
+ * ],
2216
+ * translatedFiles: [
2217
+ * { fileId: '1234567890', versionId: '1234567890', branchId: '1234567890', locale: 'es-ES' },
2218
+ * ],
2219
+ * }, {
2220
+ * timeout: 10000,
2221
+ * });
2222
+ *
2223
+ */
2224
+ async queryFileData(data, options = {}) {
2225
+ this._validateAuth("queryFileData");
2226
+ data.translatedFiles = data.translatedFiles?.map((item) => ({
2227
+ ...item,
2228
+ locale: this.resolveCanonicalLocale(item.locale)
2229
+ }));
2230
+ const result = await _queryFileData(data, options, this._getTranslationConfig());
2231
+ result.translatedFiles = result.translatedFiles?.map((item) => ({
2232
+ ...item,
2233
+ ...item.locale && { locale: this.resolveAliasLocale(item.locale) }
2234
+ }));
2235
+ result.sourceFiles = result.sourceFiles?.map((item) => ({
2236
+ ...item,
2237
+ ...item.sourceLocale && { sourceLocale: this.resolveAliasLocale(item.sourceLocale) },
2238
+ locales: item.locales.map((locale) => this.resolveAliasLocale(locale))
2239
+ }));
2240
+ return result;
2241
+ }
2242
+ /**
2243
+ * Gets source and translation information for a given file ID and version ID.
2244
+ *
2245
+ * @param {FileQuery} data - File query containing file ID and version ID.
2246
+ * @param {CheckFileTranslationsOptions} options - Options for getting source and translation information.
2247
+ * @returns {Promise<FileQueryResult>} The source file and translation information.
2248
+ *
2249
+ * @example
2250
+ * const result = await gt.querySourceFile(
2251
+ * { fileId: '1234567890', versionId: '1234567890' },
2252
+ * { timeout: 10000 }
2253
+ * );
2254
+ *
2255
+ */
2256
+ async querySourceFile(data, options = {}) {
2257
+ this._validateAuth("querySourceFile");
2258
+ const result = await _querySourceFile(data, options, this._getTranslationConfig());
2259
+ result.translations = result.translations.map((item) => ({
2260
+ ...item,
2261
+ ...item.locale && { locale: this.resolveAliasLocale(item.locale) }
2262
+ }));
2263
+ result.sourceFile.locales = result.sourceFile.locales.map((locale) => this.resolveAliasLocale(locale));
2264
+ if (result.sourceFile.sourceLocale) result.sourceFile.sourceLocale = this.resolveAliasLocale(result.sourceFile.sourceLocale);
2265
+ return result;
2266
+ }
2267
+ /**
2268
+ * Get project data for a given project ID.
2269
+ *
2270
+ * @param {string} projectId - The ID of the project to get the data for.
2271
+ * @returns {Promise<ProjectData>} The project data.
2272
+ *
2273
+ * @example
2274
+ * const result = await gt.getProjectData(
2275
+ * '1234567890'
2276
+ * );
2277
+ *
2278
+ */
2279
+ async getProjectData(projectId, options = {}) {
2280
+ this._validateAuth("getProjectData");
2281
+ const result = await _getProjectData(projectId, options, this._getTranslationConfig());
2282
+ result.currentLocales = result.currentLocales.map((item) => this.resolveAliasLocale(item));
2283
+ result.defaultLocale = this.resolveAliasLocale(result.defaultLocale);
2284
+ return result;
2285
+ }
2286
+ /**
2287
+ * Downloads a single file.
2288
+ *
2289
+ * @param file - The file query object.
2290
+ * @param {string} file.fileId - The ID of the file to download.
2291
+ * @param {string} [file.branchId] - The ID of the branch to download the file from. If not provided, the default branch will be used.
2292
+ * @param {string} [file.locale] - The locale to download the file for. If not provided, the source file will be downloaded.
2293
+ * @param {string} [file.versionId] - The version ID to download the file from. If not provided, the latest version will be used.
2294
+ * @param {DownloadFileOptions} options - Options for downloading the file.
2295
+ * @returns {Promise<string>} The downloaded file content.
2296
+ *
2297
+ * @example
2298
+ * const result = await gt.downloadFile({
2299
+ * fileId: '1234567890',
2300
+ * branchId: '1234567890',
2301
+ * locale: 'es-ES',
2302
+ * versionId: '1234567890',
2303
+ * }, {
2304
+ * timeout: 10000,
2305
+ * });
2306
+ */
2307
+ async downloadFile(file, options = {}) {
2308
+ this._validateAuth("downloadTranslatedFile");
2309
+ return (await _downloadFileBatch([{
2310
+ fileId: file.fileId,
2311
+ branchId: file.branchId,
2312
+ locale: file.locale ? this.resolveCanonicalLocale(file.locale) : void 0,
2313
+ versionId: file.versionId,
2314
+ useLatestAvailableVersion: file.useLatestAvailableVersion
2315
+ }], options, this._getTranslationConfig())).data?.[0]?.data ?? "";
2316
+ }
2317
+ /**
2318
+ * Downloads multiple files in a batch.
2319
+ *
2320
+ * @param {DownloadFileBatchRequest} requests - Array of file query objects to download.
2321
+ * @param {DownloadFileBatchOptions} options - Options for the batch download.
2322
+ * @returns {Promise<DownloadFileBatchResult>} The batch download results.
2323
+ *
2324
+ * @example
2325
+ * const result = await gt.downloadFileBatch([{
2326
+ * fileId: '1234567890',
2327
+ * locale: 'es-ES',
2328
+ * versionId: '1234567890',
2329
+ * }], {
2330
+ * timeout: 10000,
2331
+ * });
2332
+ */
2333
+ async downloadFileBatch(requests, options = {}) {
2334
+ this._validateAuth("downloadFileBatch");
2335
+ requests = requests.map((request) => ({
2336
+ ...request,
2337
+ locale: request.locale ? this.resolveCanonicalLocale(request.locale) : void 0
2338
+ }));
2339
+ const result = await _downloadFileBatch(requests, options, this._getTranslationConfig());
2340
+ return {
2341
+ files: result.data.map((file) => ({
2342
+ ...file,
2343
+ ...file.locale && { locale: this.resolveAliasLocale(file.locale) }
2344
+ })),
2345
+ count: result.count
2346
+ };
2347
+ }
2348
+ /**
2349
+ * Translates a single source string to the target locale.
2350
+ * Routes through {@link translateMany} under the hood.
2351
+ *
2352
+ * @param {string} source - The source string to translate.
2353
+ * @param {object} options - Translation options including targetLocale and optional entry metadata.
2354
+ * @returns {Promise<TranslationResult | TranslationError>} The translated content.
2355
+ *
2356
+ * @example
2357
+ * const result = await gt.translate('Hello, world!', { targetLocale: 'es' });
2358
+ *
2359
+ * @example
2360
+ * const result = await gt.translate('Hello, world!', {
2361
+ * targetLocale: 'es',
2362
+ * dataFormat: 'ICU',
2363
+ * context: 'A formal greeting',
2364
+ * });
2365
+ */
2366
+ async translate(source, options, timeout) {
2367
+ if (typeof options === "string") options = { targetLocale: options };
2368
+ this._validateAuth("translate");
2369
+ let targetLocale = options?.targetLocale || this.targetLocale;
2370
+ if (!targetLocale) {
2371
+ const error = noTargetLocaleProvidedError("translate");
2372
+ gtInstanceLogger.error(error);
2373
+ throw new Error(error);
2374
+ }
2375
+ targetLocale = this.resolveCanonicalLocale(targetLocale);
2376
+ const sourceLocale = this.resolveCanonicalLocale(options?.sourceLocale || this.sourceLocale || "en");
2377
+ return (await _translateMany([source], {
2378
+ ...options,
2379
+ targetLocale,
2380
+ sourceLocale
2381
+ }, this._getTranslationConfig(), timeout))[0];
2382
+ }
2383
+ async translateMany(sources, options, timeout) {
2384
+ if (typeof options === "string") options = { targetLocale: options };
2385
+ this._validateAuth("translateMany");
2386
+ let targetLocale = options?.targetLocale || this.targetLocale;
2387
+ if (!targetLocale) {
2388
+ const error = noTargetLocaleProvidedError("translateMany");
2389
+ gtInstanceLogger.error(error);
2390
+ throw new Error(error);
2391
+ }
2392
+ targetLocale = this.resolveCanonicalLocale(targetLocale);
2393
+ const sourceLocale = this.resolveCanonicalLocale(options?.sourceLocale || this.sourceLocale || "en");
2394
+ return await _translateMany(sources, {
2395
+ ...options,
2396
+ targetLocale,
2397
+ sourceLocale
2398
+ }, this._getTranslationConfig(), timeout);
2399
+ }
2400
+ /**
2401
+ * Uploads source files to the translation service without any translation content.
2402
+ *
2403
+ * This method creates or replaces source file entries in your project. Each uploaded
2404
+ * file becomes a source that can later be translated into target languages. The files
2405
+ * are processed and stored as base entries that serve as the foundation for generating
2406
+ * translations through the translation workflow.
2407
+ *
2408
+ * @param {Array<{source: FileUpload}>} files - Array of objects containing source file data to upload
2409
+ * @param {UploadFilesOptions} options - Configuration options including source locale and other upload settings
2410
+ * @returns {Promise<UploadFilesResponse>} Upload result containing file IDs, version information, and upload status
2411
+ */
2412
+ async uploadSourceFiles(files, options) {
2413
+ this._validateAuth("uploadSourceFiles");
2414
+ const mergedOptions = {
2415
+ ...options,
2416
+ sourceLocale: this.resolveCanonicalLocale(options.sourceLocale ?? this.sourceLocale ?? "en")
2417
+ };
2418
+ files = files.map((f) => ({
2419
+ ...f,
2420
+ source: {
2421
+ ...f.source,
2422
+ locale: this.resolveCanonicalLocale(f.source.locale)
2423
+ }
2424
+ }));
2425
+ const result = await _uploadSourceFiles(files, mergedOptions, this._getTranslationConfig());
2426
+ return {
2427
+ uploadedFiles: result.data,
2428
+ count: result.count,
2429
+ message: `Successfully uploaded ${result.count} files in ${result.batchCount} batch(es)`
2430
+ };
2431
+ }
2432
+ /**
2433
+ * Uploads translation files that correspond to previously uploaded source files.
2434
+ *
2435
+ * This method allows you to provide translated content for existing source files in your project.
2436
+ * Each translation must reference an existing source file and include the translated content
2437
+ * along with the target locale information. This is used when you have pre-existing translations
2438
+ * that you want to upload directly rather than generating them through the translation service.
2439
+ *
2440
+ * @param {Array<{source: FileUpload, translations: FileUpload[]}>} files - Array of file objects where:
2441
+ * - `source`: Reference to the existing source file (contains IDs but no content)
2442
+ * - `translations`: Array of translated files, each containing content, locale, and reference IDs
2443
+ * @param {UploadFilesOptions} options - Configuration options including source locale and upload settings
2444
+ * @returns {Promise<UploadFilesResponse>} Upload result containing translation IDs, status, and processing information
2445
+ */
2446
+ async uploadTranslations(files, options) {
2447
+ this._validateAuth("uploadTranslations");
2448
+ const mergedOptions = {
2449
+ ...options,
2450
+ sourceLocale: options.sourceLocale ?? this.sourceLocale
2451
+ };
2452
+ if (!mergedOptions.sourceLocale) {
2453
+ const error = noSourceLocaleProvidedError("uploadTranslations");
2454
+ gtInstanceLogger.error(error);
2455
+ throw new Error(error);
2456
+ }
2457
+ const result = await _uploadTranslations(files.map((f) => ({
2458
+ ...f,
2459
+ translations: f.translations.map((t) => ({
2460
+ ...t,
2461
+ locale: this.resolveCanonicalLocale(t.locale)
2462
+ }))
2463
+ })), mergedOptions, this._getTranslationConfig());
2464
+ return {
2465
+ uploadedFiles: result.data,
2466
+ count: result.count,
2467
+ message: `Successfully uploaded ${result.count} files in ${result.batchCount} batch(es)`
2468
+ };
2469
+ }
2470
+ /**
2471
+ * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.
2472
+ *
2473
+ * This method uses the GT instance's rendering locales by default for locale-specific terminator selection,
2474
+ * but can be overridden with custom locales in the options.
2475
+ *
2476
+ * @param {string} value - The string value to format with cutoff behavior.
2477
+ * @param {Object} [options] - Configuration options for cutoff formatting.
2478
+ * @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales.
2479
+ * @param {number} [options.maxChars] - The maximum number of characters to display.
2480
+ * - Undefined values are treated as no cutoff.
2481
+ * - Negative values follow .slice() behavior and terminator will be added before the value.
2482
+ * - 0 will result in an empty string.
2483
+ * - If cutoff results in an empty string, no terminator is added.
2484
+ * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.
2485
+ * @param {string} [options.terminator] - Optional override the terminator to use.
2486
+ * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.
2487
+ * - If no terminator is provided, then separator is ignored.
2488
+ * @returns {string} The formatted string with terminator applied if cutoff occurs.
2489
+ *
2490
+ * @example
2491
+ * const gt = new GT({ targetLocale: 'en-US' });
2492
+ * gt.formatCutoff('Hello, world!', { maxChars: 8 });
2493
+ * // Returns: 'Hello, w...'
2494
+ *
2495
+ * @example
2496
+ * gt.formatCutoff('Hello, world!', { maxChars: -3 });
2497
+ * // Returns: '...ld!'
2498
+ */
2499
+ formatCutoff(value, options) {
2500
+ return formatCutoff(value, {
2501
+ locales: this._renderingLocales,
2502
+ ...options
2503
+ });
2504
+ }
2505
+ /**
2506
+ * Formats a message according to the specified locales and options.
2507
+ *
2508
+ * @param {string} message - The message to format.
2509
+ * @param {string | string[]} [locales='en'] - The locales to use for formatting.
2510
+ * @param {FormatVariables} [variables={}] - The variables to use for formatting.
2511
+ * @param {StringFormat} [dataFormat='ICU'] - The format of the message.
2512
+ * @returns {string} The formatted message.
2513
+ *
2514
+ * @example
2515
+ * gt.formatMessage('Hello {name}', { name: 'John' });
2516
+ * // Returns: "Hello John"
2517
+ *
2518
+ * gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });
2519
+ * // Returns: "Bonjour John"
2520
+ */
2521
+ formatMessage(message, options) {
2522
+ return formatMessage(message, {
2523
+ locales: this._renderingLocales,
2524
+ ...options
2525
+ });
2526
+ }
2527
+ /**
2528
+ * Formats a number according to the specified locales and options.
2529
+ *
2530
+ * @param {number} number - The number to format
2531
+ * @param {Object} [options] - Additional options for number formatting
2532
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2533
+ * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options
2534
+ * @returns {string} The formatted number
2535
+ *
2536
+ * @example
2537
+ * gt.formatNum(1234.56, { style: 'currency', currency: 'USD' });
2538
+ * // Returns: "$1,234.56"
2539
+ */
2540
+ formatNum(number, options) {
2541
+ return formatNum(number, {
2542
+ locales: this._renderingLocales,
2543
+ ...options
2544
+ });
2545
+ }
2546
+ /**
2547
+ * Formats a date according to the specified locales and options.
2548
+ *
2549
+ * @param {Date} date - The date to format
2550
+ * @param {Object} [options] - Additional options for date formatting
2551
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2552
+ * @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options
2553
+ * @returns {string} The formatted date
2554
+ *
2555
+ * @example
2556
+ * gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' });
2557
+ * // Returns: "Thursday, March 14, 2024 at 2:30:45 PM GMT-7"
2558
+ */
2559
+ formatDateTime(date, options) {
2560
+ return formatDateTime(date, {
2561
+ locales: this._renderingLocales,
2562
+ ...options
2563
+ });
2564
+ }
2565
+ /**
2566
+ * Formats a currency value according to the specified locales and options.
2567
+ *
2568
+ * @param {number} value - The currency value to format
2569
+ * @param {string} currency - The currency code (e.g., 'USD', 'EUR')
2570
+ * @param {Object} [options] - Additional options for currency formatting
2571
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2572
+ * @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options
2573
+ * @returns {string} The formatted currency value
2574
+ *
2575
+ * @example
2576
+ * gt.formatCurrency(1234.56, 'USD', { style: 'currency' });
2577
+ * // Returns: "$1,234.56"
2578
+ */
2579
+ formatCurrency(value, currency, options) {
2580
+ return formatCurrency(value, currency, {
2581
+ locales: this._renderingLocales,
2582
+ ...options
2583
+ });
2584
+ }
2585
+ /**
2586
+ * Formats a list of items according to the specified locales and options.
2587
+ *
2588
+ * @param {Array<string | number>} array - The list of items to format
2589
+ * @param {Object} [options] - Additional options for list formatting
2590
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2591
+ * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options
2592
+ * @returns {string} The formatted list
2593
+ *
2594
+ * @example
2595
+ * gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' });
2596
+ * // Returns: "apple, banana, and orange"
2597
+ */
2598
+ formatList(array, options) {
2599
+ return _formatList({
2600
+ value: array,
2601
+ locales: options?.locales || this._renderingLocales,
2602
+ options
2603
+ });
2604
+ }
2605
+ /**
2606
+ * Formats a list of items according to the specified locales and options.
2607
+ * @param {Array<T>} array - The list of items to format
2608
+ * @param {Object} [options] - Additional options for list formatting
2609
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2610
+ * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options
2611
+ * @returns {Array<T | string>} The formatted list parts
2612
+ *
2613
+ * @example
2614
+ * gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] });
2615
+ * // Returns: ['apple', ', ', 42, ' and ', '{ foo: "bar" }']
2616
+ */
2617
+ formatListToParts(array, options) {
2618
+ return _formatListToParts({
2619
+ value: array,
2620
+ locales: options?.locales || this._renderingLocales,
2621
+ options
2622
+ });
2623
+ }
2624
+ /**
2625
+ * Formats a relative time value according to the specified locales and options.
2626
+ *
2627
+ * @param {number} value - The relative time value to format
2628
+ * @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year')
2629
+ * @param {Object} options - Additional options for relative time formatting
2630
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2631
+ * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options
2632
+ * @returns {string} The formatted relative time string
2633
+ *
2634
+ * @example
2635
+ * gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' });
2636
+ * // Returns: "yesterday"
2637
+ */
2638
+ formatRelativeTime(value, unit, options) {
2639
+ return formatRelativeTime(value, unit, {
2640
+ locales: this._renderingLocales,
2641
+ ...options
2642
+ });
2643
+ }
2644
+ /**
2645
+ * Formats a relative time string from a Date, automatically selecting the best unit.
2646
+ *
2647
+ * @param {Date} date - The date to format relative to now
2648
+ * @param {Object} [options] - Additional options for relative time formatting
2649
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
2650
+ * @returns {string} The formatted relative time string (e.g., "2 hours ago", "in 3 days")
2651
+ *
2652
+ * @example
2653
+ * gt.formatRelativeTimeFromDate(new Date(Date.now() - 3600000));
2654
+ * // Returns: "1 hour ago"
2655
+ */
2656
+ formatRelativeTimeFromDate(date, options) {
2657
+ return formatRelativeTimeFromDate(date, {
2658
+ locales: this._renderingLocales,
2659
+ ...options
2660
+ });
2661
+ }
2662
+ /**
2663
+ * Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found.
2664
+ *
2665
+ * @param {string} [locale=this.targetLocale] - A BCP-47 locale code
2666
+ * @returns {string} The display name corresponding to the code
2667
+ * @throws {Error} If no target locale is provided
2668
+ *
2669
+ * @example
2670
+ * gt.getLocaleName('es-ES');
2671
+ * // Returns: "Spanish (Spain)"
2672
+ */
2673
+ getLocaleName(locale = this.targetLocale) {
2674
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleName"));
2675
+ return _getLocaleName(locale, this.sourceLocale, this.customMapping);
2676
+ }
2677
+ /**
2678
+ * Retrieves an emoji based on a given locale code.
2679
+ * Uses the locale's region (if present) to select an emoji or falls back on default emojis.
2680
+ *
2681
+ * @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA')
2682
+ * @returns {string} The emoji representing the locale or its region
2683
+ * @throws {Error} If no target locale is provided
2684
+ *
2685
+ * @example
2686
+ * gt.getLocaleEmoji('es-ES');
2687
+ * // Returns: "🇪🇸"
2688
+ */
2689
+ getLocaleEmoji(locale = this.targetLocale) {
2690
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleEmoji"));
2691
+ return getLocaleEmoji(locale, this.customMapping);
2692
+ }
2693
+ /**
2694
+ * Generates linguistic details for a given locale code.
2695
+ *
2696
+ * This function returns information about the locale,
2697
+ * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).
2698
+ * The function provides these names in both your default language and native forms, and an associated emoji.
2699
+ *
2700
+ * @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., "de-AT").
2701
+ * @returns {LocaleProperties} - An object containing detailed information about the locale.
2702
+ *
2703
+ * @property {string} code - The full locale code, e.g., "de-AT".
2704
+ * @property {string} name - Language name in the default display language, e.g., "Austrian German".
2705
+ * @property {string} nativeName - Language name in the locale's native language, e.g., "Österreichisches Deutsch".
2706
+ * @property {string} languageCode - The base language code, e.g., "de".
2707
+ * @property {string} languageName - The language name in the default display language, e.g., "German".
2708
+ * @property {string} nativeLanguageName - The language name in the native language, e.g., "Deutsch".
2709
+ * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., "German (AT)".
2710
+ * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., "Deutsch (AT)".
2711
+ * @property {string} regionCode - The region code from maximization, e.g., "AT".
2712
+ * @property {string} regionName - The region name in the default display language, e.g., "Austria".
2713
+ * @property {string} nativeRegionName - The region name in the native language, e.g., "Österreich".
2714
+ * @property {string} scriptCode - The script code from maximization, e.g., "Latn".
2715
+ * @property {string} scriptName - The script name in the default display language, e.g., "Latin".
2716
+ * @property {string} nativeScriptName - The script name in the native language, e.g., "Lateinisch".
2717
+ * @property {string} maximizedCode - The maximized locale code, e.g., "de-Latn-AT".
2718
+ * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., "Austrian German (Latin)".
2719
+ * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., "Österreichisches Deutsch (Lateinisch)".
2720
+ * @property {string} minimizedCode - Minimized locale code, e.g., "de-AT" (or "de" for "de-DE").
2721
+ * @property {string} minimizedName - Minimized language name in the default language, e.g., "Austrian German".
2722
+ * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., "Österreichisches Deutsch".
2723
+ * @property {string} emoji - The emoji associated with the locale's region, if applicable.
2724
+ */
2725
+ getLocaleProperties(locale = this.targetLocale) {
2726
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleProperties"));
2727
+ return getLocaleProperties(locale, this.sourceLocale, this.customMapping);
2728
+ }
2729
+ /**
2730
+ * Retrieves multiple properties for a given region code, including:
2731
+ * - `code`: the original region code
2732
+ * - `name`: the localized display name
2733
+ * - `emoji`: the associated flag or symbol
2734
+ *
2735
+ * Behavior:
2736
+ * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
2737
+ * - Uses the instance's `targetLocale` to localize the region name for the user.
2738
+ * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
2739
+ * - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`.
2740
+ * - Falls back to the region code as `name` if display name resolution fails.
2741
+ * - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`.
2742
+ *
2743
+ * @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
2744
+ * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
2745
+ * @returns {{ code: string, name: string, emoji: string }} An object containing:
2746
+ * - `code`: the input region code
2747
+ * - `name`: the localized or custom region name
2748
+ * - `emoji`: the matching emoji flag or symbol
2749
+ *
2750
+ * @throws {Error} If no target locale is available to determine region properties.
2751
+ *
2752
+ * @example
2753
+ * const gt = new GT({ targetLocale: 'en-US' });
2754
+ * gt.getRegionProperties('US');
2755
+ * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
2756
+ *
2757
+ * @example
2758
+ * const gt = new GT({ targetLocale: 'fr-FR' });
2759
+ * gt.getRegionProperties('US');
2760
+ * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
2761
+ *
2762
+ * @example
2763
+ * gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } });
2764
+ * // => { code: 'US', name: 'USA', emoji: '🗽' }
2765
+ */
2766
+ getRegionProperties(region = this.getLocaleProperties().regionCode, customMapping) {
2767
+ if (!customMapping) {
2768
+ if (this.customMapping && !this.customRegionMapping) {
2769
+ const customRegionMapping = {};
2770
+ for (const [locale, lp] of Object.entries(this.customMapping)) if (lp && typeof lp === "object" && lp.regionCode && !customRegionMapping[lp.regionCode]) {
2771
+ const { regionName: name, emoji } = lp;
2772
+ customRegionMapping[lp.regionCode] = {
2773
+ locale,
2774
+ ...name && { name },
2775
+ ...emoji && { emoji }
2776
+ };
2777
+ }
2778
+ this.customRegionMapping = customRegionMapping;
2779
+ }
2780
+ customMapping = this.customRegionMapping;
2781
+ }
2782
+ return _getRegionProperties(region, this.targetLocale, customMapping);
2783
+ }
2784
+ /**
2785
+ * Determines whether a translation is required based on the source and target locales.
2786
+ *
2787
+ * @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content
2788
+ * @param {string} [targetLocale=this.targetLocale] - The locale code to translate into
2789
+ * @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales
2790
+ * @returns {boolean} True if translation is required, false otherwise
2791
+ * @throws {Error} If no source locale is provided
2792
+ * @throws {Error} If no target locale is provided
2793
+ *
2794
+ * @example
2795
+ * gt.requiresTranslation('en-US', 'es-ES');
2796
+ * // Returns: true
2797
+ */
2798
+ requiresTranslation(sourceLocale = this.sourceLocale, targetLocale = this.targetLocale, approvedLocales = this.locales, customMapping = this.customMapping) {
2799
+ if (!sourceLocale) throw new Error(noSourceLocaleProvidedError("requiresTranslation"));
2800
+ if (!targetLocale) throw new Error(noTargetLocaleProvidedError("requiresTranslation"));
2801
+ return _requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping);
2802
+ }
2803
+ /**
2804
+ * Determines the best matching locale from the provided approved locales list.
2805
+ *
2806
+ * @param {string | string[]} locales - A single locale or array of locales in preference order
2807
+ * @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order
2808
+ * @returns {string | undefined} The best matching locale or undefined if no match is found
2809
+ *
2810
+ * @example
2811
+ * gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']);
2812
+ * // Returns: "fr-FR"
2813
+ */
2814
+ determineLocale(locales, approvedLocales = this.locales || [], customMapping = this.customMapping) {
2815
+ return _determineLocale(locales, approvedLocales, customMapping);
2816
+ }
2817
+ /**
2818
+ * Gets the text direction for a given locale code.
2819
+ *
2820
+ * @param {string} [locale=this.targetLocale] - A BCP-47 locale code
2821
+ * @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left, otherwise 'ltr'
2822
+ * @throws {Error} If no target locale is provided
2823
+ *
2824
+ * @example
2825
+ * gt.getLocaleDirection('ar-SA');
2826
+ * // Returns: "rtl"
2827
+ */
2828
+ getLocaleDirection(locale = this.targetLocale) {
2829
+ if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleDirection"));
2830
+ return getLocaleDirection(locale);
2831
+ }
2832
+ /**
2833
+ * Checks if a given BCP 47 locale code is valid.
2834
+ *
2835
+ * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate
2836
+ * @param {customMapping} [customMapping=this.customMapping] - The custom mapping to use for validation
2837
+ * @returns {boolean} True if the locale code is valid, false otherwise
2838
+ * @throws {Error} If no target locale is provided
2839
+ *
2840
+ * @example
2841
+ * gt.isValidLocale('en-US');
2842
+ * // Returns: true
2843
+ */
2844
+ isValidLocale(locale = this.targetLocale, customMapping = this.customMapping) {
2845
+ if (!locale) throw new Error(noTargetLocaleProvidedError("isValidLocale"));
2846
+ return isValidLocale(locale, customMapping);
2847
+ }
2848
+ /**
2849
+ * Resolves the canonical locale for a given locale.
2850
+ * @param locale - The locale to resolve the canonical locale for
2851
+ * @param customMapping - The custom mapping to use for resolving the canonical locale
2852
+ * @returns The canonical locale
2853
+ */
2854
+ resolveCanonicalLocale(locale = this.targetLocale, customMapping = this.customMapping) {
2855
+ if (!locale) throw new Error(noTargetLocaleProvidedError("resolveCanonicalLocale"));
2856
+ return _resolveCanonicalLocale(locale, customMapping);
2857
+ }
2858
+ /**
2859
+ * Resolves the alias locale for a given locale.
2860
+ * @param locale - The locale to resolve the alias locale for
2861
+ * @param customMapping - The custom mapping to use for resolving the alias locale
2862
+ * @returns The alias locale
2863
+ */
2864
+ resolveAliasLocale(locale, customMapping = this.customMapping) {
2865
+ if (!locale) throw new Error(noTargetLocaleProvidedError("resolveAliasLocale"));
2866
+ return _resolveAliasLocale(locale, customMapping);
2867
+ }
2868
+ /**
2869
+ * Standardizes a BCP 47 locale code to ensure correct formatting.
2870
+ *
2871
+ * @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize
2872
+ * @returns {string} The standardized locale code or empty string if invalid
2873
+ * @throws {Error} If no target locale is provided
2874
+ *
2875
+ * @example
2876
+ * gt.standardizeLocale('en_us');
2877
+ * // Returns: "en-US"
2878
+ */
2879
+ standardizeLocale(locale = this.targetLocale) {
2880
+ if (!locale) throw new Error(noTargetLocaleProvidedError("standardizeLocale"));
2881
+ return _standardizeLocale(locale);
2882
+ }
2883
+ /**
2884
+ * Checks if multiple BCP 47 locale codes represent the same dialect.
2885
+ *
2886
+ * @param {...(string | string[])} locales - The BCP 47 locale codes to compare
2887
+ * @returns {boolean} True if all codes represent the same dialect, false otherwise
2888
+ *
2889
+ * @example
2890
+ * gt.isSameDialect('en-US', 'en-GB');
2891
+ * // Returns: false
2892
+ *
2893
+ * gt.isSameDialect('en', 'en-US');
2894
+ * // Returns: true
2895
+ */
2896
+ isSameDialect(...locales) {
2897
+ return isSameDialect(...locales);
2898
+ }
2899
+ /**
2900
+ * Checks if multiple BCP 47 locale codes represent the same language.
2901
+ *
2902
+ * @param {...(string | string[])} locales - The BCP 47 locale codes to compare
2903
+ * @returns {boolean} True if all codes represent the same language, false otherwise
2904
+ *
2905
+ * @example
2906
+ * gt.isSameLanguage('en-US', 'en-GB');
2907
+ * // Returns: true
2908
+ */
2909
+ isSameLanguage(...locales) {
2910
+ return _isSameLanguage(...locales);
2911
+ }
2912
+ /**
2913
+ * Checks if a locale is a superset of another locale.
2914
+ *
2915
+ * @param {string} superLocale - The locale to check if it is a superset
2916
+ * @param {string} subLocale - The locale to check if it is a subset
2917
+ * @returns {boolean} True if superLocale is a superset of subLocale, false otherwise
2918
+ *
2919
+ * @example
2920
+ * gt.isSupersetLocale('en', 'en-US');
2921
+ * // Returns: true
2922
+ *
2923
+ * gt.isSupersetLocale('en-US', 'en');
2924
+ * // Returns: false
2925
+ */
2926
+ isSupersetLocale(superLocale, subLocale) {
2927
+ return isSupersetLocale(superLocale, subLocale);
2928
+ }
2929
+ };
2930
+ /**
2931
+ * Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.
2932
+ *
2933
+ * This standalone function provides cutoff formatting functionality without requiring a GT instance.
2934
+ * The locales parameter is required for proper terminator selection based on the target language.
2935
+ *
2936
+ * @param {string} value - The string value to format with cutoff behavior.
2937
+ * @param {Object} [options] - Configuration options for cutoff formatting.
2938
+ * @param {string | string[]} [options.locales] - The locales to use for terminator selection.
2939
+ * @param {number} [options.maxChars] - The maximum number of characters to display.
2940
+ * - Undefined values are treated as no cutoff.
2941
+ * - Negative values follow .slice() behavior and terminator will be added before the value.
2942
+ * - 0 will result in an empty string.
2943
+ * - If cutoff results in an empty string, no terminator is added.
2944
+ * @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.
2945
+ * @param {string} [options.terminator] - Optional override the terminator to use.
2946
+ * @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.
2947
+ * - If no terminator is provided, then separator is ignored.
2948
+ * @returns {string} The formatted string with terminator applied if cutoff occurs.
2949
+ *
2950
+ * @example
2951
+ * formatCutoff('Hello, world!', { locales: 'en-US', maxChars: 8 });
2952
+ * // Returns: 'Hello, w...'
2953
+ *
2954
+ * @example
2955
+ * formatCutoff('Hello, world!', { locales: 'en-US', maxChars: -3 });
2956
+ * // Returns: '...ld!'
2957
+ *
2958
+ * @example
2959
+ * formatCutoff('Very long text that needs cutting', {
2960
+ * locales: 'en-US',
2961
+ * maxChars: 15,
2962
+ * style: 'ellipsis',
2963
+ * separator: ' '
2964
+ * });
2965
+ * // Returns: 'Very long text ...'
2966
+ */
2967
+ function formatCutoff(value, options) {
2968
+ return _formatCutoff({
2969
+ value,
2970
+ locales: options?.locales,
2971
+ options
2972
+ });
2973
+ }
2974
+ /**
2975
+ * Formats a message according to the specified locales and options.
2976
+ *
2977
+ * @param {string} message - The message to format.
2978
+ * @param {string | string[]} [locales='en'] - The locales to use for formatting.
2979
+ * @param {FormatVariables} [variables={}] - The variables to use for formatting.
2980
+ * @param {StringFormat} [dataFormat='ICU'] - The format of the message. (When STRING, the message is returned as is)
2981
+ * @returns {string} The formatted message.
2982
+ *
2983
+ * @example
2984
+ * formatMessage('Hello {name}', { name: 'John' });
2985
+ * // Returns: "Hello John"
2986
+ *
2987
+ * formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });
2988
+ * // Returns: "Bonjour John"
2989
+ */
2990
+ function formatMessage(message, options) {
2991
+ switch (options?.dataFormat) {
2992
+ case "STRING": return _formatMessageString(message);
2993
+ default: return _formatMessageICU(message, options?.locales, options?.variables);
2994
+ }
2995
+ }
2996
+ /**
2997
+ * Formats a number according to the specified locales and options.
2998
+ * @param {Object} params - The parameters for the number formatting.
2999
+ * @param {number} params.value - The number to format.
3000
+ * @param {Intl.NumberFormatOptions} [params.options] - Additional options for number formatting.
3001
+ * @param {string | string[]} [params.options.locales] - The locales to use for formatting.
3002
+ * @returns {string} The formatted number.
3003
+ */
3004
+ function formatNum(number, options) {
3005
+ return _formatNum({
3006
+ value: number,
3007
+ locales: options.locales,
3008
+ options
3009
+ });
3010
+ }
3011
+ /**
3012
+ * Formats a date according to the specified languages and options.
3013
+ * @param {Object} params - The parameters for the date formatting.
3014
+ * @param {Date} params.value - The date to format.
3015
+ * @param {Intl.DateTimeFormatOptions} [params.options] - Additional options for date formatting.
3016
+ * @param {string | string[]} [params.options.locales] - The languages to use for formatting.
3017
+ * @returns {string} The formatted date.
3018
+ */
3019
+ function formatDateTime(date, options) {
3020
+ return _formatDateTime({
3021
+ value: date,
3022
+ locales: options?.locales,
3023
+ options
3024
+ });
3025
+ }
3026
+ /**
3027
+ * Formats a currency value according to the specified languages, currency, and options.
3028
+ * @param {Object} params - The parameters for the currency formatting.
3029
+ * @param {number} params.value - The currency value to format.
3030
+ * @param {string} params.currency - The currency code (e.g., 'USD').
3031
+ * @param {Intl.NumberFormatOptions} [params.options={}] - Additional options for currency formatting.
3032
+ * @param {string | string[]} [params.options.locales] - The locale codes to use for formatting.
3033
+ * @returns {string} The formatted currency value.
3034
+ */
3035
+ function formatCurrency(value, currency, options) {
3036
+ return _formatCurrency({
3037
+ value,
3038
+ currency,
3039
+ locales: options.locales,
3040
+ options
3041
+ });
3042
+ }
3043
+ /**
3044
+ * Formats a list of items according to the specified locales and options.
3045
+ * @param {Object} params - The parameters for the list formatting.
3046
+ * @param {Array<string | number>} params.value - The list of items to format.
3047
+ * @param {Intl.ListFormatOptions} [params.options={}] - Additional options for list formatting.
3048
+ * @param {string | string[]} [params.options.locales] - The locales to use for formatting.
3049
+ * @returns {string} The formatted list.
3050
+ */
3051
+ function formatList(array, options) {
3052
+ return _formatList({
3053
+ value: array,
3054
+ locales: options.locales,
3055
+ options
3056
+ });
3057
+ }
3058
+ /**
3059
+ * Formats a list of items according to the specified locales and options.
3060
+ * @param {Array<T>} array - The list of items to format
3061
+ * @param {Object} [options] - Additional options for list formatting
3062
+ * @param {string | string[]} [options.locales] - The locales to use for formatting
3063
+ * @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options
3064
+ * @returns {Array<T | string>} The formatted list parts
3065
+ */
3066
+ function formatListToParts(array, options) {
3067
+ return _formatListToParts({
3068
+ value: array,
3069
+ locales: options?.locales,
3070
+ options
3071
+ });
3072
+ }
3073
+ /**
3074
+ * Formats a relative time value according to the specified locales and options.
3075
+ * @param {Object} params - The parameters for the relative time formatting.
3076
+ * @param {number} params.value - The relative time value to format.
3077
+ * @param {Intl.RelativeTimeFormatUnit} params.unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year').
3078
+ * @param {Intl.RelativeTimeFormatOptions} [params.options={}] - Additional options for relative time formatting.
3079
+ * @param {string | string[]} [params.options.locales] - The locales to use for formatting.
3080
+ * @returns {string} The formatted relative time string.
3081
+ */
3082
+ function formatRelativeTime(value, unit, options) {
3083
+ return _formatRelativeTime({
3084
+ value,
3085
+ unit,
3086
+ locales: options.locales,
3087
+ options
3088
+ });
3089
+ }
3090
+ /**
3091
+ * Formats a relative time string from a Date, automatically selecting the best unit.
3092
+ * @param {Date} date - The date to format relative to now.
3093
+ * @param {Object} options - Formatting options.
3094
+ * @param {string | string[]} options.locales - The locales to use for formatting.
3095
+ * @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options.
3096
+ * @returns {string} The formatted relative time string (e.g., "2 hours ago", "in 3 days").
3097
+ */
3098
+ function formatRelativeTimeFromDate(date, options) {
3099
+ const { locales, baseDate, ...intlOptions } = options;
3100
+ return _formatRelativeTimeFromDate({
3101
+ date,
3102
+ baseDate: baseDate ?? /* @__PURE__ */ new Date(),
3103
+ locales,
3104
+ options: intlOptions
3105
+ });
3106
+ }
3107
+ /**
3108
+ * Retrieves the display name of locale code using Intl.DisplayNames.
3109
+ *
3110
+ * @param {string} locale - A BCP-47 locale code.
3111
+ * @param {string} [defaultLocale] - The default locale to use for formatting.
3112
+ * @param {CustomMapping} [customMapping] - A custom mapping of locale codes to their names.
3113
+ * @returns {string} The display name corresponding to the code.
3114
+ */
3115
+ function getLocaleName(locale, defaultLocale, customMapping) {
3116
+ return _getLocaleName(locale, defaultLocale, customMapping);
3117
+ }
3118
+ /**
3119
+ * Retrieves an emoji based on a given locale code, taking into account region, language, and specific exceptions.
3120
+ *
3121
+ * This function uses the locale's region (if present) to select an emoji or falls back on default emojis for certain languages.
3122
+ *
3123
+ * @param locale - A string representing the locale code (e.g., 'en-US', 'fr-CA').
3124
+ * @param {CustomMapping} [customMapping] - A custom mapping of locale codes to their names.
3125
+ * @returns The emoji representing the locale or its region, or a default emoji if no specific match is found.
3126
+ */
3127
+ function getLocaleEmoji(locale, customMapping) {
3128
+ return _getLocaleEmoji(locale, customMapping);
3129
+ }
3130
+ /**
3131
+ * Generates linguistic details for a given locale code.
3132
+ *
3133
+ * This function returns information about the locale,
3134
+ * script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).
3135
+ * The function provides these names in both your default language and native forms, and an associated emoji.
3136
+ *
3137
+ * @param {string} locale - The locale code to get properties for (e.g., "de-AT").
3138
+ * @param {string} [defaultLocale] - The default locale to use for formatting.
3139
+ * @param {CustomMapping} [customMapping] - A custom mapping of locale codes to their names.
3140
+ * @returns {LocaleProperties} - An object containing detailed information about the locale.
3141
+ *
3142
+ * @property {string} code - The full locale code, e.g., "de-AT".
3143
+ * @property {string} name - Language name in the default display language, e.g., "Austrian German".
3144
+ * @property {string} nativeName - Language name in the locale's native language, e.g., "Österreichisches Deutsch".
3145
+ * @property {string} languageCode - The base language code, e.g., "de".
3146
+ * @property {string} languageName - The language name in the default display language, e.g., "German".
3147
+ * @property {string} nativeLanguageName - The language name in the native language, e.g., "Deutsch".
3148
+ * @property {string} nameWithRegionCode - Language name with region in the default language, e.g., "German (AT)".
3149
+ * @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., "Deutsch (AT)".
3150
+ * @property {string} regionCode - The region code from maximization, e.g., "AT".
3151
+ * @property {string} regionName - The region name in the default display language, e.g., "Austria".
3152
+ * @property {string} nativeRegionName - The region name in the native language, e.g., "Österreich".
3153
+ * @property {string} scriptCode - The script code from maximization, e.g., "Latn".
3154
+ * @property {string} scriptName - The script name in the default display language, e.g., "Latin".
3155
+ * @property {string} nativeScriptName - The script name in the native language, e.g., "Lateinisch".
3156
+ * @property {string} maximizedCode - The maximized locale code, e.g., "de-Latn-AT".
3157
+ * @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., "Austrian German (Latin)".
3158
+ * @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., "Österreichisches Deutsch (Lateinisch)".
3159
+ * @property {string} minimizedCode - Minimized locale code, e.g., "de-AT" (or "de" for "de-DE").
3160
+ * @property {string} minimizedName - Minimized language name in the default language, e.g., "Austrian German".
3161
+ * @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., "Österreichisches Deutsch".
3162
+ * @property {string} emoji - The emoji associated with the locale's region, if applicable.
3163
+ */
3164
+ function getLocaleProperties(locale, defaultLocale, customMapping) {
3165
+ return _getLocaleProperties(locale, defaultLocale, customMapping);
3166
+ }
3167
+ /**
3168
+ * Retrieves multiple properties for a given region code, including:
3169
+ * - `code`: the original region code
3170
+ * - `name`: the localized display name
3171
+ * - `emoji`: the associated flag or symbol
3172
+ *
3173
+ * Behavior:
3174
+ * - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
3175
+ * - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
3176
+ * - Otherwise, uses `Intl.DisplayNames` to get the localized region name in the given `defaultLocale`,
3177
+ * falling back to `libraryDefaultLocale`.
3178
+ * - Falls back to the region code as `name` if display name resolution fails.
3179
+ * - Falls back to `defaultEmoji` if no emoji mapping is found in `emojis` or `customMapping`.
3180
+ *
3181
+ * @param {string} region - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
3182
+ * @param {string} [defaultLocale=libraryDefaultLocale] - The locale to use when localizing the region name.
3183
+ * @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
3184
+ * @returns {{ code: string, name: string, emoji: string }} An object containing:
3185
+ * - `code`: the input region code
3186
+ * - `name`: the localized or custom region name
3187
+ * - `emoji`: the matching emoji flag or symbol
3188
+ *
3189
+ * @example
3190
+ * getRegionProperties('US', 'en');
3191
+ * // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
3192
+ *
3193
+ * @example
3194
+ * getRegionProperties('US', 'fr');
3195
+ * // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
3196
+ *
3197
+ * @example
3198
+ * getRegionProperties('US', 'en', { US: { name: 'USA', emoji: '🗽' } });
3199
+ * // => { code: 'US', name: 'USA', emoji: '🗽' }
3200
+ */
3201
+ function getRegionProperties(region, defaultLocale, customMapping) {
3202
+ return _getRegionProperties(region, defaultLocale, customMapping);
3203
+ }
3204
+ /**
3205
+ * Determines whether a translation is required based on the source and target locales.
3206
+ *
3207
+ * - If the target locale is not specified, the function returns `false`, as translation is not needed.
3208
+ * - If the source and target locale are the same, returns `false`, indicating that no translation is necessary.
3209
+ * - If the `approvedLocales` array is provided, and the target locale is not within that array, the function also returns `false`.
3210
+ * - Otherwise, it returns `true`, meaning that a translation is required.
3211
+ *
3212
+ * @param {string} sourceLocale - The locale code for the original content (BCP 47 locale code).
3213
+ * @param {string} targetLocale - The locale code of the language to translate the content into (BCP 47 locale code).
3214
+ * @param {string[]} [approvedLocale] - An optional array of approved target locales.
3215
+ *
3216
+ * @returns {boolean} - Returns `true` if translation is required, otherwise `false`.
3217
+ */
3218
+ function requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping) {
3219
+ return _requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping);
3220
+ }
3221
+ /**
3222
+ * Determines the best matching locale from the provided approved locales list.
3223
+ * @param {string | string[]} locales - A single locale or an array of locales sorted in preference order.
3224
+ * @param {string[]} [approvedLocales=this.locales] - An array of approved locales, also sorted by preference.
3225
+ * @returns {string | undefined} - The best matching locale from the approvedLocales list, or undefined if no match is found.
3226
+ */
3227
+ function determineLocale(locales, approvedLocales = [], customMapping = void 0) {
3228
+ return _determineLocale(locales, approvedLocales, customMapping);
3229
+ }
3230
+ /**
3231
+ * Get the text direction for a given locale code using the Intl.Locale API.
3232
+ *
3233
+ * @param {string} locale - A BCP-47 locale code.
3234
+ * @returns {string} - 'rtl' if the locale is right-to-left, otherwise 'ltr'.
3235
+ */
3236
+ function getLocaleDirection(locale) {
3237
+ return _getLocaleDirection(locale);
3238
+ }
3239
+ /**
3240
+ * Checks if a given BCP 47 locale code is valid.
3241
+ * @param {string} locale - The BCP 47 locale code to validate.
3242
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for validation.
3243
+ * @returns {boolean} True if the BCP 47 code is valid, false otherwise.
3244
+ */
3245
+ function isValidLocale(locale, customMapping) {
3246
+ return _isValidLocale(locale, customMapping);
3247
+ }
3248
+ /**
3249
+ * Resolves the alias locale for a given locale.
3250
+ * @param {string} locale - The locale to resolve the alias locale for
3251
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for resolving the alias locale
3252
+ * @returns {string} The alias locale
3253
+ */
3254
+ function resolveAliasLocale(locale, customMapping) {
3255
+ return _resolveAliasLocale(locale, customMapping);
3256
+ }
3257
+ /**
3258
+ * Resolves the canonical locale for a given locale.
3259
+ * @param {string} locale - The locale to resolve the canonical locale for
3260
+ * @param {CustomMapping} [customMapping] - The custom mapping to use for resolving the canonical locale
3261
+ * @returns {string} The canonical locale
3262
+ */
3263
+ function resolveCanonicalLocale(locale, customMapping) {
3264
+ return _resolveCanonicalLocale(locale, customMapping);
3265
+ }
3266
+ /**
3267
+ * Standardizes a BCP 47 locale code to ensure correct formatting.
3268
+ * @param {string} locale - The BCP 47 locale code to standardize.
3269
+ * @returns {string} The standardized BCP 47 locale code or an empty string if it is an invalid code.
3270
+ */
3271
+ function standardizeLocale(locale) {
3272
+ return _standardizeLocale(locale);
3273
+ }
3274
+ /**
3275
+ * Checks if multiple BCP 47 locale codes represent the same dialect.
3276
+ * @param {string[]} locales - The BCP 47 locale codes to compare.
3277
+ * @returns {boolean} True if all BCP 47 codes represent the same dialect, false otherwise.
3278
+ */
3279
+ function isSameDialect(...locales) {
3280
+ return _isSameDialect(...locales);
3281
+ }
3282
+ /**
3283
+ * Checks if multiple BCP 47 locale codes represent the same language.
3284
+ * @param {string[]} locales - The BCP 47 locale codes to compare.
3285
+ * @returns {boolean} True if all BCP 47 codes represent the same language, false otherwise.
3286
+ */
3287
+ function isSameLanguage(...locales) {
3288
+ return _isSameLanguage(...locales);
3289
+ }
3290
+ /**
3291
+ * Checks if a locale is a superset of another locale.
3292
+ * A subLocale is a subset of superLocale if it is an extension of superLocale or are otherwise identical.
3293
+ *
3294
+ * @param {string} superLocale - The locale to check if it is a superset of the other locale.
3295
+ * @param {string} subLocale - The locale to check if it is a subset of the other locale.
3296
+ * @returns {boolean} True if the first locale is a superset of the second locale, false otherwise.
3297
+ */
3298
+ function isSupersetLocale(superLocale, subLocale) {
3299
+ return _isSupersetLocale(superLocale, subLocale);
3300
+ }
3301
+ const API_VERSION = API_VERSION$1;
3302
+ //#endregion
3303
+ export { API_VERSION, GT, determineLocale, formatCurrency, formatCutoff, formatDateTime, formatList, formatListToParts, formatMessage, formatNum, formatRelativeTime, formatRelativeTimeFromDate, getLocaleDirection, getLocaleEmoji, getLocaleName, getLocaleProperties, getRegionProperties, isSameDialect, isSameLanguage, isSupersetLocale, isValidLocale, requiresTranslation, resolveAliasLocale, resolveCanonicalLocale, standardizeLocale };
3304
+
3305
+ //# sourceMappingURL=index.mjs.map