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