generaltranslation 9.4.2 → 9.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +2 -1
- package/dist/{ApiError-BcjcnTAr.cjs → ApiError-BCjEo_CM.cjs} +1 -1
- package/dist/{ApiError-BcjcnTAr.cjs.map → ApiError-BCjEo_CM.cjs.map} +1 -1
- package/dist/{ApiError-CUKcz3YS.mjs → ApiError-DxWKM0Xt.mjs} +1 -1
- package/dist/{ApiError-CUKcz3YS.mjs.map → ApiError-DxWKM0Xt.mjs.map} +1 -1
- package/dist/adapter/createGtApi.d.ts +196 -27
- package/dist/adapter/createGtApi.js +561 -117
- package/dist/adapter/modelProvider.d.ts +4 -0
- package/dist/adapter/modelProvider.js +6 -0
- package/dist/derive-Cv5_y8Tf.mjs +656 -0
- package/dist/derive-Cv5_y8Tf.mjs.map +1 -0
- package/dist/{derive-DBCCXTmL.d.cts → derive-J2NQLqZm.d.cts} +1 -1
- package/dist/derive-t_E3ftJN.cjs +733 -0
- package/dist/derive-t_E3ftJN.cjs.map +1 -0
- package/dist/diagnostics-CqAHg_Vc.d.cts +34 -0
- package/dist/diagnostics-DKA2SkZB.mjs +45 -0
- package/dist/diagnostics-DKA2SkZB.mjs.map +1 -0
- package/dist/{unwrapApiResult-BzGfPw75.mjs → diagnostics-DKtiPUvo.cjs} +12 -31
- package/dist/diagnostics-DKtiPUvo.cjs.map +1 -0
- package/dist/diagnostics-DYtVjOm5.d.mts +34 -0
- package/dist/diagnostics.cjs +4 -0
- package/dist/diagnostics.d.cts +2 -0
- package/dist/diagnostics.d.mts +2 -0
- package/dist/diagnostics.d.ts +1 -0
- package/dist/diagnostics.js +1 -0
- package/dist/diagnostics.mjs +2 -0
- package/dist/errors.cjs +1 -1
- package/dist/errors.mjs +1 -1
- package/dist/file-B37WkCqM.cjs.map +1 -1
- package/dist/file-Dga6cyM8.mjs.map +1 -1
- package/dist/{id-X2zyx5Jk.mjs → id-B2wA7-S-.mjs} +19 -3
- package/dist/id-B2wA7-S-.mjs.map +1 -0
- package/dist/{id-pdr3R1xs.cjs → id-DJ_59q21.cjs} +25 -3
- package/dist/id-DJ_59q21.cjs.map +1 -0
- package/dist/id.cjs +1 -1
- package/dist/id.d.cts +1 -1
- package/dist/id.d.mts +1 -1
- package/dist/id.mjs +1 -1
- package/dist/index.cjs +94 -753
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -33
- package/dist/index.d.mts +13 -32
- package/dist/index.d.ts +20 -16
- package/dist/index.js +110 -98
- package/dist/index.mjs +88 -746
- package/dist/index.mjs.map +1 -1
- package/dist/internal.cjs +16 -186
- package/dist/internal.cjs.map +1 -1
- package/dist/internal.d.cts +200 -62
- package/dist/internal.d.mts +199 -61
- package/dist/internal.d.ts +3 -1
- package/dist/internal.js +2 -1
- package/dist/internal.mjs +6 -178
- package/dist/internal.mjs.map +1 -1
- package/dist/logging/errors.d.ts +0 -1
- package/dist/logging/errors.js +0 -6
- package/dist/logging/logger.js +6 -4
- package/dist/openapi.json +2344 -845
- package/dist/runtime.cjs +580 -2
- package/dist/runtime.cjs.map +1 -0
- package/dist/runtime.d.cts +12 -6
- package/dist/runtime.d.mts +12 -6
- package/dist/runtime.d.ts +10 -4
- package/dist/runtime.js +10 -65
- package/dist/runtime.mjs +579 -1
- package/dist/runtime.mjs.map +1 -0
- package/dist/runtimeTranslate-CVw143pQ.mjs +506 -0
- package/dist/runtimeTranslate-CVw143pQ.mjs.map +1 -0
- package/dist/runtimeTranslate-DJioRjb6.cjs +601 -0
- package/dist/runtimeTranslate-DJioRjb6.cjs.map +1 -0
- package/dist/translate/awaitJobs.d.ts +2 -2
- package/dist/translate/awaitJobs.js +1 -156
- package/dist/translate/checkJobStatus.d.ts +2 -1
- package/dist/translate/checkJobStatus.js +1 -55
- package/dist/translate/createBranch.d.ts +2 -6
- package/dist/translate/createBranch.js +1 -53
- package/dist/translate/enqueueFiles.js +1 -95
- package/dist/translate/getProjectInfo.d.ts +2 -6
- package/dist/translate/getProjectInfo.js +1 -54
- package/dist/translate/processFileMoves.d.ts +3 -13
- package/dist/translate/processFileMoves.js +1 -90
- package/dist/translate/publishFiles.d.ts +3 -15
- package/dist/translate/publishFiles.js +1 -56
- package/dist/translate/queryBranchData.js +1 -53
- package/dist/translate/queryFileData.d.ts +3 -41
- package/dist/translate/queryFileData.js +1 -71
- package/dist/translate/runtimeTranslate.d.ts +6 -0
- package/dist/translate/runtimeTranslate.js +297 -0
- package/dist/translate/setupProject.d.ts +2 -6
- package/dist/translate/setupProject.js +1 -63
- package/dist/translate/submitUserEditDiffs.js +1 -68
- package/dist/translate/utils/fetchWithTimeout.js +19 -12
- package/dist/{types-bCr8pV1Z.d.cts → types-Si4UstLL.d.mts} +41 -165
- package/dist/types-dir/__tests__/runtimeTranslate.type-test.js +18 -0
- package/dist/types-dir/api/branch.d.ts +3 -9
- package/dist/types-dir/api/checkFileTranslations.d.ts +2 -22
- package/dist/types-dir/api/downloadFileBatch.d.ts +2 -7
- package/dist/types-dir/api/entry.d.ts +3 -8
- package/dist/types-dir/api/file.d.ts +2 -1
- package/dist/types-dir/api/json.d.ts +1 -4
- package/dist/types-dir/api/project.d.ts +2 -7
- package/dist/types-dir/api/uploadAssets.d.ts +3 -10
- package/dist/types-dir/api/uploadAssets.js +0 -4
- package/dist/types-dir/config.d.ts +1 -0
- package/dist/{types-Dp1drjxq.d.mts → types-yByDbKnV.d.cts} +41 -165
- package/dist/types.d.cts +2 -2
- package/dist/types.d.mts +2 -2
- package/dist/types.d.ts +26 -7
- package/package.json +15 -2
- package/dist/derive-2CDqwrvS.cjs +0 -303
- package/dist/derive-2CDqwrvS.cjs.map +0 -1
- package/dist/derive-CTzR56T_.mjs +0 -233
- package/dist/derive-CTzR56T_.mjs.map +0 -1
- package/dist/id-X2zyx5Jk.mjs.map +0 -1
- package/dist/id-pdr3R1xs.cjs.map +0 -1
- package/dist/isVariable-8-Wy5FnX.mjs +0 -20
- package/dist/isVariable-8-Wy5FnX.mjs.map +0 -1
- package/dist/isVariable-I3nllgeI.cjs +0 -25
- package/dist/isVariable-I3nllgeI.cjs.map +0 -1
- package/dist/projects/getProjectData.js +0 -87
- package/dist/runtime-Bcp4F2ME.mjs +0 -974
- package/dist/runtime-Bcp4F2ME.mjs.map +0 -1
- package/dist/runtime-C25lwh9m.cjs +0 -1027
- package/dist/runtime-C25lwh9m.cjs.map +0 -1
- package/dist/translate/api.d.ts +0 -4
- package/dist/translate/api.js +0 -4
- package/dist/translate/createTag.d.ts +0 -19
- package/dist/translate/createTag.js +0 -67
- package/dist/translate/downloadFileBatch.d.ts +0 -1
- package/dist/translate/downloadFileBatch.js +0 -80
- package/dist/translate/getOrphanedFiles.d.ts +0 -8
- package/dist/translate/getOrphanedFiles.js +0 -97
- package/dist/translate/querySourceFile.d.ts +0 -1
- package/dist/translate/querySourceFile.js +0 -67
- package/dist/translate/translateMany.d.ts +0 -1
- package/dist/translate/translateMany.js +0 -124
- package/dist/translate/uploadFonts.d.ts +0 -1
- package/dist/translate/uploadFonts.js +0 -74
- package/dist/translate/uploadSourceFiles.d.ts +0 -1
- package/dist/translate/uploadSourceFiles.js +0 -90
- package/dist/translate/uploadTranslations.d.ts +0 -1
- package/dist/translate/uploadTranslations.js +0 -106
- package/dist/translate/utils/apiRequest.d.ts +0 -1
- package/dist/translate/utils/apiRequest.js +0 -167
- package/dist/translate/utils/generateRequestHeaders.d.ts +0 -2
- package/dist/translate/utils/generateRequestHeaders.js +0 -21
- package/dist/translate/utils/handleFetchError.d.ts +0 -1
- package/dist/translate/utils/handleFetchError.js +0 -12
- package/dist/unwrapApiResult-BzGfPw75.mjs.map +0 -1
- package/dist/unwrapApiResult-Dv6Mfw_K.cjs +0 -134
- package/dist/unwrapApiResult-Dv6Mfw_K.cjs.map +0 -1
- /package/dist/{projects/getProjectData.d.ts → types-dir/__tests__/runtimeTranslate.type-test.d.ts} +0 -0
|
@@ -1,974 +0,0 @@
|
|
|
1
|
-
import { l as defaultTimeout, r as unwrapApiResult, s as createDiagnosticMessage, t as hasDecodedError } from "./unwrapApiResult-BzGfPw75.mjs";
|
|
2
|
-
import { t as ApiError } from "./ApiError-CUKcz3YS.mjs";
|
|
3
|
-
import { t as hashSource } from "./id-X2zyx5Jk.mjs";
|
|
4
|
-
import { createApiClient, translate } from "@generaltranslation/api";
|
|
5
|
-
import { LocaleConfig, getRegionProperties, isValidLocale, requiresTranslation, resolveAliasLocale, resolveCanonicalLocale } from "@generaltranslation/format";
|
|
6
|
-
//#region src/logging/errors.ts
|
|
7
|
-
const GT_SOURCE = "GT";
|
|
8
|
-
const translationTimeoutError = (timeout) => createDiagnosticMessage({
|
|
9
|
-
source: GT_SOURCE,
|
|
10
|
-
severity: "Error",
|
|
11
|
-
whatHappened: `Translation request timed out after ${timeout}ms`,
|
|
12
|
-
fix: "Try again, or increase the request timeout if the source content is large"
|
|
13
|
-
});
|
|
14
|
-
const translationRequestFailedError = (error) => createDiagnosticMessage({
|
|
15
|
-
source: GT_SOURCE,
|
|
16
|
-
severity: "Error",
|
|
17
|
-
whatHappened: "Translation request could not be completed",
|
|
18
|
-
fix: "Check your network connection and translation credentials, then try again",
|
|
19
|
-
details: error
|
|
20
|
-
});
|
|
21
|
-
const apiError = (status, statusText, error) => createDiagnosticMessage({
|
|
22
|
-
source: GT_SOURCE,
|
|
23
|
-
severity: "Error",
|
|
24
|
-
whatHappened: `The translation API returned ${status} ${statusText}`,
|
|
25
|
-
fix: "Check the request configuration and try again",
|
|
26
|
-
details: error
|
|
27
|
-
});
|
|
28
|
-
createDiagnosticMessage({
|
|
29
|
-
source: GT_SOURCE,
|
|
30
|
-
severity: "Error",
|
|
31
|
-
whatHappened: "Authentication failed",
|
|
32
|
-
fix: "Check that your API key and project ID are correct"
|
|
33
|
-
});
|
|
34
|
-
const noTargetLocaleProvidedError = (functionName) => createDiagnosticMessage({
|
|
35
|
-
source: GT_SOURCE,
|
|
36
|
-
severity: "Error",
|
|
37
|
-
whatHappened: `Cannot call \`${functionName}\` without a specified locale`,
|
|
38
|
-
fix: `Pass a locale to \`${functionName}\` or specify targetLocale in the GT constructor`
|
|
39
|
-
});
|
|
40
|
-
const noSourceLocaleProvidedError = (functionName) => createDiagnosticMessage({
|
|
41
|
-
source: GT_SOURCE,
|
|
42
|
-
severity: "Error",
|
|
43
|
-
whatHappened: `Cannot call \`${functionName}\` without a specified locale`,
|
|
44
|
-
fix: `Pass a locale to \`${functionName}\` or specify sourceLocale in the GT constructor`
|
|
45
|
-
});
|
|
46
|
-
const noProjectIdProvidedError = (functionName) => createDiagnosticMessage({
|
|
47
|
-
source: GT_SOURCE,
|
|
48
|
-
severity: "Error",
|
|
49
|
-
whatHappened: `Cannot call \`${functionName}\` without a specified project ID`,
|
|
50
|
-
fix: `Pass a project ID to \`${functionName}\` or specify projectId in the GT constructor`
|
|
51
|
-
});
|
|
52
|
-
const noApiKeyProvidedError = (functionName) => createDiagnosticMessage({
|
|
53
|
-
source: GT_SOURCE,
|
|
54
|
-
severity: "Error",
|
|
55
|
-
whatHappened: `Cannot call \`${functionName}\` without a specified API key`,
|
|
56
|
-
fix: `Pass an API key to \`${functionName}\` or specify apiKey in the GT constructor`
|
|
57
|
-
});
|
|
58
|
-
const invalidLocaleError = (locale) => createDiagnosticMessage({
|
|
59
|
-
source: GT_SOURCE,
|
|
60
|
-
severity: "Error",
|
|
61
|
-
whatHappened: `Locale "${locale}" is not valid`,
|
|
62
|
-
fix: "Use a valid BCP 47 locale code or add a custom mapping"
|
|
63
|
-
});
|
|
64
|
-
const invalidLocalesError = (locales) => createDiagnosticMessage({
|
|
65
|
-
source: GT_SOURCE,
|
|
66
|
-
severity: "Error",
|
|
67
|
-
whatHappened: `These locales are not valid: ${locales.join(", ")}`,
|
|
68
|
-
fix: "Use valid BCP 47 locale codes or add custom mappings"
|
|
69
|
-
});
|
|
70
|
-
//#endregion
|
|
71
|
-
//#region src/logging/logger.ts
|
|
72
|
-
const LOG_LEVELS = {
|
|
73
|
-
debug: 0,
|
|
74
|
-
info: 1,
|
|
75
|
-
warn: 2,
|
|
76
|
-
error: 3,
|
|
77
|
-
off: 4
|
|
78
|
-
};
|
|
79
|
-
const LOG_COLORS = {
|
|
80
|
-
debug: "\x1B[36m",
|
|
81
|
-
info: "\x1B[32m",
|
|
82
|
-
warn: "\x1B[33m",
|
|
83
|
-
error: "\x1B[31m",
|
|
84
|
-
off: ""
|
|
85
|
-
};
|
|
86
|
-
const RESET_COLOR = "\x1B[0m";
|
|
87
|
-
/**
|
|
88
|
-
* Get the configured log level from environment variable or default to 'warn'
|
|
89
|
-
*/
|
|
90
|
-
function getConfiguredLogLevel() {
|
|
91
|
-
if (typeof process !== "undefined" && process.env?._GT_LOG_LEVEL) {
|
|
92
|
-
const envLevel = process.env._GT_LOG_LEVEL.toLowerCase();
|
|
93
|
-
if (envLevel in LOG_LEVELS) return envLevel;
|
|
94
|
-
}
|
|
95
|
-
return "warn";
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* Console log handler that outputs formatted messages to console
|
|
99
|
-
*/
|
|
100
|
-
var ConsoleLogHandler = class {
|
|
101
|
-
constructor(config) {
|
|
102
|
-
this.config = config;
|
|
103
|
-
}
|
|
104
|
-
handle(entry) {
|
|
105
|
-
const parts = [];
|
|
106
|
-
if (this.config.includeTimestamp) parts.push(`[${entry.timestamp.toISOString()}]`);
|
|
107
|
-
const colorCode = LOG_COLORS[entry.level];
|
|
108
|
-
const levelText = `[${entry.level.toUpperCase()}]`;
|
|
109
|
-
parts.push(`${colorCode}${levelText}${RESET_COLOR}`);
|
|
110
|
-
if (this.config.prefix) parts.push(`[${this.config.prefix}]`);
|
|
111
|
-
if (this.config.includeContext && entry.context) parts.push(`[${entry.context}]`);
|
|
112
|
-
parts.push(entry.message);
|
|
113
|
-
if (entry.metadata && Object.keys(entry.metadata).length > 0) parts.push(`\n Metadata: ${JSON.stringify(entry.metadata, null, 2)}`);
|
|
114
|
-
const formattedMessage = parts.join(" ");
|
|
115
|
-
switch (entry.level) {
|
|
116
|
-
case "debug":
|
|
117
|
-
console.debug(formattedMessage);
|
|
118
|
-
break;
|
|
119
|
-
case "info":
|
|
120
|
-
console.info(formattedMessage);
|
|
121
|
-
break;
|
|
122
|
-
case "warn":
|
|
123
|
-
console.warn(formattedMessage);
|
|
124
|
-
break;
|
|
125
|
-
case "error":
|
|
126
|
-
console.error(formattedMessage);
|
|
127
|
-
break;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
};
|
|
131
|
-
/**
|
|
132
|
-
* Main Logger class providing structured logging capabilities.
|
|
133
|
-
*/
|
|
134
|
-
var Logger = class {
|
|
135
|
-
constructor(config = {}) {
|
|
136
|
-
this.config = {
|
|
137
|
-
level: getConfiguredLogLevel(),
|
|
138
|
-
includeTimestamp: true,
|
|
139
|
-
includeContext: true,
|
|
140
|
-
enableConsole: true,
|
|
141
|
-
handlers: [],
|
|
142
|
-
...config
|
|
143
|
-
};
|
|
144
|
-
this.handlers = [...this.config.handlers || []];
|
|
145
|
-
if (this.config.enableConsole) this.handlers.push(new ConsoleLogHandler(this.config));
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* Add a custom log handler
|
|
149
|
-
*/
|
|
150
|
-
addHandler(handler) {
|
|
151
|
-
this.handlers.push(handler);
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* Remove a log handler
|
|
155
|
-
*/
|
|
156
|
-
removeHandler(handler) {
|
|
157
|
-
const index = this.handlers.indexOf(handler);
|
|
158
|
-
if (index > -1) this.handlers.splice(index, 1);
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Update logger configuration
|
|
162
|
-
*/
|
|
163
|
-
configure(config) {
|
|
164
|
-
this.config = {
|
|
165
|
-
...this.config,
|
|
166
|
-
...config
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
/**
|
|
170
|
-
* Check if a log level should be output based on current configuration
|
|
171
|
-
*/
|
|
172
|
-
shouldLog(level) {
|
|
173
|
-
return LOG_LEVELS[level] >= LOG_LEVELS[this.config.level];
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Internal logging method that creates log entries and passes them to handlers
|
|
177
|
-
*/
|
|
178
|
-
log(level, message, context, metadata) {
|
|
179
|
-
if (!this.shouldLog(level)) return;
|
|
180
|
-
const entry = {
|
|
181
|
-
level,
|
|
182
|
-
message,
|
|
183
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
184
|
-
context,
|
|
185
|
-
metadata
|
|
186
|
-
};
|
|
187
|
-
this.handlers.forEach((handler) => {
|
|
188
|
-
try {
|
|
189
|
-
handler.handle(entry);
|
|
190
|
-
} catch (error) {
|
|
191
|
-
console.error("Error in log handler:", error);
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* Log a debug message
|
|
197
|
-
* Used for detailed diagnostic information, typically of interest only when diagnosing problems
|
|
198
|
-
*/
|
|
199
|
-
debug(message, context, metadata) {
|
|
200
|
-
this.log("debug", message, context, metadata);
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Log an info message
|
|
204
|
-
* Used for general information about application operation.
|
|
205
|
-
*/
|
|
206
|
-
info(message, context, metadata) {
|
|
207
|
-
this.log("info", message, context, metadata);
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Log a warning message
|
|
211
|
-
* Used for potentially problematic situations that don't prevent operation
|
|
212
|
-
*/
|
|
213
|
-
warn(message, context, metadata) {
|
|
214
|
-
this.log("warn", message, context, metadata);
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Log an error message
|
|
218
|
-
* Used for error events that might still allow the application to continue.
|
|
219
|
-
*/
|
|
220
|
-
error(message, context, metadata) {
|
|
221
|
-
this.log("error", message, context, metadata);
|
|
222
|
-
}
|
|
223
|
-
/**
|
|
224
|
-
* Create a child logger with a specific context
|
|
225
|
-
*/
|
|
226
|
-
child(context) {
|
|
227
|
-
return new ContextLogger(this, context);
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Get current logger configuration
|
|
231
|
-
*/
|
|
232
|
-
getConfig() {
|
|
233
|
-
return { ...this.config };
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
/**
|
|
237
|
-
* Context logger that automatically includes context information.
|
|
238
|
-
*/
|
|
239
|
-
var ContextLogger = class ContextLogger {
|
|
240
|
-
constructor(logger, context) {
|
|
241
|
-
this.logger = logger;
|
|
242
|
-
this.context = context;
|
|
243
|
-
}
|
|
244
|
-
debug(message, metadata) {
|
|
245
|
-
this.logger.debug(message, this.context, metadata);
|
|
246
|
-
}
|
|
247
|
-
info(message, metadata) {
|
|
248
|
-
this.logger.info(message, this.context, metadata);
|
|
249
|
-
}
|
|
250
|
-
warn(message, metadata) {
|
|
251
|
-
this.logger.warn(message, this.context, metadata);
|
|
252
|
-
}
|
|
253
|
-
error(message, metadata) {
|
|
254
|
-
this.logger.error(message, this.context, metadata);
|
|
255
|
-
}
|
|
256
|
-
child(childContext) {
|
|
257
|
-
return new ContextLogger(this.logger, `${this.context}:${childContext}`);
|
|
258
|
-
}
|
|
259
|
-
};
|
|
260
|
-
const defaultLogger = new Logger({
|
|
261
|
-
level: getConfiguredLogLevel(),
|
|
262
|
-
includeTimestamp: true,
|
|
263
|
-
includeContext: true,
|
|
264
|
-
prefix: "GT"
|
|
265
|
-
});
|
|
266
|
-
const fetchLogger = defaultLogger.child("fetch");
|
|
267
|
-
const gtInstanceLogger = defaultLogger.child("GT instance");
|
|
268
|
-
//#endregion
|
|
269
|
-
//#region src/translate/utils/fetchWithTimeout.ts
|
|
270
|
-
/**
|
|
271
|
-
* @internal
|
|
272
|
-
*
|
|
273
|
-
* Wraps the fetch function with a timeout.
|
|
274
|
-
*
|
|
275
|
-
* @param url - The URL to fetch.
|
|
276
|
-
* @param options - The options to pass to the fetch function.
|
|
277
|
-
* @param timeout - The timeout in milliseconds.
|
|
278
|
-
* @returns The response from the fetch function.
|
|
279
|
-
*/
|
|
280
|
-
async function fetchWithTimeout(url, options, timeout) {
|
|
281
|
-
const controller = new AbortController();
|
|
282
|
-
const signals = [controller.signal];
|
|
283
|
-
if (options.signal) signals.push(options.signal);
|
|
284
|
-
if (url instanceof Request) signals.push(url.signal);
|
|
285
|
-
const signal = AbortSignal.any(signals);
|
|
286
|
-
timeout = timeout ? timeout : defaultTimeout;
|
|
287
|
-
const timeoutId = timeout ? setTimeout(() => controller.abort(), timeout) : null;
|
|
288
|
-
try {
|
|
289
|
-
return await fetch(url, {
|
|
290
|
-
...options,
|
|
291
|
-
signal
|
|
292
|
-
});
|
|
293
|
-
} catch (error) {
|
|
294
|
-
if (error instanceof Error && error.name === "AbortError") throw translationTimeoutError(timeout);
|
|
295
|
-
throw error;
|
|
296
|
-
} finally {
|
|
297
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region src/translate/utils/validateResponse.ts
|
|
302
|
-
async function validateResponse(response) {
|
|
303
|
-
if (!response.ok) {
|
|
304
|
-
let errorMsg = "Unknown error";
|
|
305
|
-
try {
|
|
306
|
-
const text = await response.text();
|
|
307
|
-
try {
|
|
308
|
-
errorMsg = JSON.parse(text).error;
|
|
309
|
-
} catch {
|
|
310
|
-
errorMsg = text || "Unknown error";
|
|
311
|
-
}
|
|
312
|
-
} catch {}
|
|
313
|
-
throw new ApiError(apiError(response.status, response.statusText, errorMsg), response.status, errorMsg);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
//#endregion
|
|
317
|
-
//#region src/translate/translateMany.ts
|
|
318
|
-
async function _translateMany(requests, globalMetadata, config, timeout) {
|
|
319
|
-
const isArray = Array.isArray(requests);
|
|
320
|
-
const hashOrder = isArray ? [] : void 0;
|
|
321
|
-
const requestsObject = {};
|
|
322
|
-
const entries = isArray ? requests.map((r) => [void 0, r]) : Object.entries(requests);
|
|
323
|
-
for (const [key, request] of entries) {
|
|
324
|
-
const { source, metadata } = typeof request === "string" ? { source: request } : request;
|
|
325
|
-
const hash = key ?? metadata?.hash ?? hashSource({
|
|
326
|
-
source,
|
|
327
|
-
...metadata?.context && { context: metadata.context },
|
|
328
|
-
...metadata?.maxChars != null && { maxChars: metadata.maxChars },
|
|
329
|
-
...metadata?.fileFormat && { fileFormat: metadata.fileFormat },
|
|
330
|
-
dataFormat: metadata?.dataFormat ?? "STRING"
|
|
331
|
-
});
|
|
332
|
-
hashOrder?.push(hash);
|
|
333
|
-
requestsObject[hash] = {
|
|
334
|
-
source,
|
|
335
|
-
metadata
|
|
336
|
-
};
|
|
337
|
-
}
|
|
338
|
-
const client = createApiClient({
|
|
339
|
-
apiKey: config.apiKey,
|
|
340
|
-
baseUrl: config.baseUrl || "https://api.gtx.dev",
|
|
341
|
-
fetch: (input, init) => fetchWithTimeout(input, init ?? {}, timeout),
|
|
342
|
-
projectId: config.projectId,
|
|
343
|
-
retryPolicy: "none",
|
|
344
|
-
timeoutMs: false
|
|
345
|
-
});
|
|
346
|
-
const result = await translate({
|
|
347
|
-
body: {
|
|
348
|
-
requests: requestsObject,
|
|
349
|
-
targetLocale: globalMetadata.targetLocale,
|
|
350
|
-
sourceLocale: globalMetadata.sourceLocale,
|
|
351
|
-
metadata: globalMetadata
|
|
352
|
-
},
|
|
353
|
-
client
|
|
354
|
-
});
|
|
355
|
-
if (result.data === void 0 && result.response && !hasDecodedError(result)) {
|
|
356
|
-
await validateResponse(result.response);
|
|
357
|
-
throw result.error;
|
|
358
|
-
}
|
|
359
|
-
const response = unwrapApiResult(result);
|
|
360
|
-
if (hashOrder) return hashOrder.map((hash) => response[hash] ?? {
|
|
361
|
-
success: false,
|
|
362
|
-
error: "No translation returned",
|
|
363
|
-
code: 500
|
|
364
|
-
});
|
|
365
|
-
return response;
|
|
366
|
-
}
|
|
367
|
-
//#endregion
|
|
368
|
-
//#region src/runtime.ts
|
|
369
|
-
/**
|
|
370
|
-
* GTRuntime is the runtime core of the GT driver: locale management,
|
|
371
|
-
* formatting, and runtime translation requests.
|
|
372
|
-
*
|
|
373
|
-
* Browser-facing SDK code constructs this class (via `generaltranslation/runtime`)
|
|
374
|
-
* so production bundles do not ship the project/file management API client
|
|
375
|
-
* that lives on the GT class exported from the main entry.
|
|
376
|
-
*
|
|
377
|
-
* @example
|
|
378
|
-
* const gt = new GTRuntime({
|
|
379
|
-
* sourceLocale: 'en-US',
|
|
380
|
-
* targetLocale: 'es-ES',
|
|
381
|
-
* locales: ['en-US', 'es-ES', 'fr-FR']
|
|
382
|
-
* });
|
|
383
|
-
*/
|
|
384
|
-
var GTRuntime = class {
|
|
385
|
-
/** Runtime-safe locale and formatting helpers */
|
|
386
|
-
get localeConfig() {
|
|
387
|
-
return this._localeConfig;
|
|
388
|
-
}
|
|
389
|
-
/**
|
|
390
|
-
* Constructs an instance of the GTRuntime class.
|
|
391
|
-
*
|
|
392
|
-
* @param {GTConstructorParams} [params] - The parameters for initializing the GTRuntime instance
|
|
393
|
-
* @throws {Error} If an invalid locale is provided
|
|
394
|
-
* @throws {Error} If any of the provided locales are invalid
|
|
395
|
-
*
|
|
396
|
-
* @example
|
|
397
|
-
* const gt = new GTRuntime({
|
|
398
|
-
* apiKey: 'your-api-key',
|
|
399
|
-
* sourceLocale: 'en-US',
|
|
400
|
-
* targetLocale: 'es-ES',
|
|
401
|
-
* locales: ['en-US', 'es-ES', 'fr-FR']
|
|
402
|
-
* });
|
|
403
|
-
*/
|
|
404
|
-
constructor(params = {}) {
|
|
405
|
-
if (typeof process !== "undefined") {
|
|
406
|
-
this.apiKey ||= process.env?.GT_API_KEY;
|
|
407
|
-
this.devApiKey ||= process.env?.GT_DEV_API_KEY;
|
|
408
|
-
this.projectId ||= process.env?.GT_PROJECT_ID;
|
|
409
|
-
}
|
|
410
|
-
this.setConfig(params);
|
|
411
|
-
}
|
|
412
|
-
setConfig({ apiKey, devApiKey, sourceLocale, targetLocale, locales, projectId, customMapping, baseUrl }) {
|
|
413
|
-
const effectiveCustomMapping = customMapping ?? this.customMapping;
|
|
414
|
-
if (apiKey) this.apiKey = apiKey;
|
|
415
|
-
if (devApiKey) this.devApiKey = devApiKey;
|
|
416
|
-
if (projectId) this.projectId = projectId;
|
|
417
|
-
if (sourceLocale) {
|
|
418
|
-
this.sourceLocale = sourceLocale;
|
|
419
|
-
if (!isValidLocale(this.sourceLocale, effectiveCustomMapping)) throw new Error(invalidLocaleError(this.sourceLocale));
|
|
420
|
-
}
|
|
421
|
-
if (targetLocale) {
|
|
422
|
-
this.targetLocale = targetLocale;
|
|
423
|
-
if (!isValidLocale(this.targetLocale, effectiveCustomMapping)) throw new Error(invalidLocaleError(this.targetLocale));
|
|
424
|
-
}
|
|
425
|
-
if (locales) {
|
|
426
|
-
const result = [];
|
|
427
|
-
const invalidLocales = [];
|
|
428
|
-
locales.forEach((locale) => {
|
|
429
|
-
if (isValidLocale(locale, effectiveCustomMapping)) result.push(locale);
|
|
430
|
-
else invalidLocales.push(locale);
|
|
431
|
-
});
|
|
432
|
-
if (invalidLocales.length > 0) throw new Error(invalidLocalesError(invalidLocales));
|
|
433
|
-
this.locales = result;
|
|
434
|
-
}
|
|
435
|
-
if (baseUrl) this.baseUrl = baseUrl;
|
|
436
|
-
if (customMapping) {
|
|
437
|
-
this.customMapping = customMapping;
|
|
438
|
-
this.reverseCustomMapping = Object.fromEntries(Object.entries(customMapping).filter(([, value]) => value && typeof value === "object" && "code" in value).map(([key, value]) => [value.code, key]));
|
|
439
|
-
}
|
|
440
|
-
this._localeConfig = new LocaleConfig({
|
|
441
|
-
defaultLocale: this.sourceLocale,
|
|
442
|
-
locales: this.locales ?? [],
|
|
443
|
-
customMapping: this.customMapping
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
/** Convert app identity only where a GT service expects a language code. */
|
|
447
|
-
resolveServiceLocale(locale) {
|
|
448
|
-
return this.standardizeLocale(this.resolveCanonicalLocale(locale));
|
|
449
|
-
}
|
|
450
|
-
/**
|
|
451
|
-
* Recover configured spelling without negotiating an unrelated dialect.
|
|
452
|
-
* When several identities use the same service code and there is no request
|
|
453
|
-
* context to disambiguate them, the first configured identity wins.
|
|
454
|
-
*/
|
|
455
|
-
resolveServiceResponseLocale(locale) {
|
|
456
|
-
const canonical = this.standardizeLocale(locale);
|
|
457
|
-
return [
|
|
458
|
-
...this.locales ?? [],
|
|
459
|
-
this.sourceLocale,
|
|
460
|
-
this.targetLocale,
|
|
461
|
-
...Object.keys(this.customMapping ?? {})
|
|
462
|
-
].find((candidate) => candidate && this.resolveServiceLocale(candidate) === canonical) ?? locale;
|
|
463
|
-
}
|
|
464
|
-
_getTranslationConfig() {
|
|
465
|
-
return {
|
|
466
|
-
baseUrl: this.baseUrl,
|
|
467
|
-
apiKey: this.apiKey || this.devApiKey,
|
|
468
|
-
projectId: this.projectId || ""
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
_validateAuth(functionName) {
|
|
472
|
-
const errors = [];
|
|
473
|
-
if (!this.apiKey && !this.devApiKey) {
|
|
474
|
-
const error = noApiKeyProvidedError(functionName);
|
|
475
|
-
errors.push(error);
|
|
476
|
-
}
|
|
477
|
-
if (!this.projectId) {
|
|
478
|
-
const error = noProjectIdProvidedError(functionName);
|
|
479
|
-
errors.push(error);
|
|
480
|
-
}
|
|
481
|
-
if (errors.length) throw new Error(errors.join("\n"));
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Translates a single source string to the target locale.
|
|
485
|
-
* Routes through {@link translateMany} under the hood.
|
|
486
|
-
*
|
|
487
|
-
* @param {string} source - The source string to translate.
|
|
488
|
-
* @param {object} options - Translation options including targetLocale and optional entry metadata.
|
|
489
|
-
* @returns {Promise<TranslationResult | TranslationError>} The translated content.
|
|
490
|
-
*
|
|
491
|
-
* @example
|
|
492
|
-
* const result = await gt.translate('Hello, world!', { targetLocale: 'es' });
|
|
493
|
-
*
|
|
494
|
-
* @example
|
|
495
|
-
* const result = await gt.translate('Hello, world!', {
|
|
496
|
-
* targetLocale: 'es',
|
|
497
|
-
* dataFormat: 'ICU',
|
|
498
|
-
* context: 'A formal greeting',
|
|
499
|
-
* });
|
|
500
|
-
*/
|
|
501
|
-
async translate(source, options, timeout) {
|
|
502
|
-
if (typeof options === "string") options = { targetLocale: options };
|
|
503
|
-
this._validateAuth("translate");
|
|
504
|
-
let targetLocale = options?.targetLocale || this.targetLocale;
|
|
505
|
-
if (!targetLocale) {
|
|
506
|
-
const error = noTargetLocaleProvidedError("translate");
|
|
507
|
-
gtInstanceLogger.error(error);
|
|
508
|
-
throw new Error(error);
|
|
509
|
-
}
|
|
510
|
-
targetLocale = this.resolveServiceLocale(targetLocale);
|
|
511
|
-
const sourceLocale = this.resolveServiceLocale(options?.sourceLocale || this.sourceLocale || "en");
|
|
512
|
-
return (await _translateMany([source], {
|
|
513
|
-
...options,
|
|
514
|
-
targetLocale,
|
|
515
|
-
sourceLocale
|
|
516
|
-
}, this._getTranslationConfig(), timeout))[0];
|
|
517
|
-
}
|
|
518
|
-
async translateMany(sources, options, timeout) {
|
|
519
|
-
if (typeof options === "string") options = { targetLocale: options };
|
|
520
|
-
this._validateAuth("translateMany");
|
|
521
|
-
let targetLocale = options?.targetLocale || this.targetLocale;
|
|
522
|
-
if (!targetLocale) {
|
|
523
|
-
const error = noTargetLocaleProvidedError("translateMany");
|
|
524
|
-
gtInstanceLogger.error(error);
|
|
525
|
-
throw new Error(error);
|
|
526
|
-
}
|
|
527
|
-
targetLocale = this.resolveServiceLocale(targetLocale);
|
|
528
|
-
const sourceLocale = this.resolveServiceLocale(options?.sourceLocale || this.sourceLocale || "en");
|
|
529
|
-
return await _translateMany(sources, {
|
|
530
|
-
...options,
|
|
531
|
-
targetLocale,
|
|
532
|
-
sourceLocale
|
|
533
|
-
}, this._getTranslationConfig(), timeout);
|
|
534
|
-
}
|
|
535
|
-
/**
|
|
536
|
-
* Formats a string with cutoff behavior, applying a terminator when the string exceeds the maximum character limit.
|
|
537
|
-
*
|
|
538
|
-
* This method uses the GT instance's rendering locales by default for locale-specific terminator selection,
|
|
539
|
-
* but can be overridden with custom locales in the options.
|
|
540
|
-
*
|
|
541
|
-
* @param {string} value - The string value to format with cutoff behavior.
|
|
542
|
-
* @param {Object} [options] - Configuration options for cutoff formatting.
|
|
543
|
-
* @param {string | string[]} [options.locales] - The locales to use for terminator selection. Defaults to instance's rendering locales.
|
|
544
|
-
* @param {number} [options.maxChars] - The maximum number of characters to display.
|
|
545
|
-
* - Undefined values are treated as no cutoff.
|
|
546
|
-
* - Negative values follow .slice() behavior and terminator will be added before the value.
|
|
547
|
-
* - 0 will result in an empty string.
|
|
548
|
-
* - If cutoff results in an empty string, no terminator is added.
|
|
549
|
-
* @param {CutoffFormatStyle} [options.style='ellipsis'] - The style of the terminator.
|
|
550
|
-
* @param {string} [options.terminator] - Optional override the terminator to use.
|
|
551
|
-
* @param {string} [options.separator] - Optional override the separator to use between the terminator and the value.
|
|
552
|
-
* - If no terminator is provided, then separator is ignored.
|
|
553
|
-
* @returns {string} The formatted string with terminator applied if cutoff occurs.
|
|
554
|
-
*
|
|
555
|
-
* @example
|
|
556
|
-
* const gt = new GTRuntime({ targetLocale: 'en-US' });
|
|
557
|
-
* gt.formatCutoff('Hello, world!', { maxChars: 8 });
|
|
558
|
-
* // Returns: 'Hello, w...'
|
|
559
|
-
*
|
|
560
|
-
* @example
|
|
561
|
-
* gt.formatCutoff('Hello, world!', { maxChars: -3 });
|
|
562
|
-
* // Returns: '...ld!'
|
|
563
|
-
*/
|
|
564
|
-
formatCutoff(value, options) {
|
|
565
|
-
return this.localeConfig.formatCutoff(value, this.targetLocale, options);
|
|
566
|
-
}
|
|
567
|
-
/**
|
|
568
|
-
* Formats a message according to the specified locales and options.
|
|
569
|
-
*
|
|
570
|
-
* @param {string} message - The message to format.
|
|
571
|
-
* @param {string | string[]} [locales=libraryDefaultLocale] - The locales to use for formatting.
|
|
572
|
-
* @param {FormatVariables} [variables={}] - The variables to use for formatting.
|
|
573
|
-
* @param {StringFormat} [dataFormat='ICU'] - The format of the message.
|
|
574
|
-
* @returns {string} The formatted message.
|
|
575
|
-
*
|
|
576
|
-
* @example
|
|
577
|
-
* gt.formatMessage('Hello {name}', { name: 'John' });
|
|
578
|
-
* // Returns: "Hello John"
|
|
579
|
-
*
|
|
580
|
-
* gt.formatMessage('Hello {name}', { name: 'John' }, { locales: ['fr'] });
|
|
581
|
-
* // Returns: "Bonjour John"
|
|
582
|
-
*/
|
|
583
|
-
formatMessage(message, options) {
|
|
584
|
-
return this.localeConfig.formatMessage(message, this.targetLocale, options);
|
|
585
|
-
}
|
|
586
|
-
/**
|
|
587
|
-
* Formats a number according to the specified locales and options.
|
|
588
|
-
*
|
|
589
|
-
* @param {number} number - The number to format.
|
|
590
|
-
* @param {Object} [options] - Additional options for number formatting.
|
|
591
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
592
|
-
* @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.
|
|
593
|
-
* @returns {string} The formatted number.
|
|
594
|
-
*
|
|
595
|
-
* @example
|
|
596
|
-
* gt.formatNum(1234.56, { style: 'currency', currency: 'USD' });
|
|
597
|
-
* // Returns: "$1,234.56"
|
|
598
|
-
*/
|
|
599
|
-
formatNum(number, options) {
|
|
600
|
-
return this.localeConfig.formatNum(number, this.targetLocale, options);
|
|
601
|
-
}
|
|
602
|
-
/**
|
|
603
|
-
* Formats a date according to the specified locales and options.
|
|
604
|
-
*
|
|
605
|
-
* @param {Date} date - The date to format.
|
|
606
|
-
* @param {Object} [options] - Additional options for date formatting.
|
|
607
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
608
|
-
* @param {Intl.DateTimeFormatOptions} [options] - Additional Intl.DateTimeFormat options.
|
|
609
|
-
* @returns {string} The formatted date.
|
|
610
|
-
*
|
|
611
|
-
* @example
|
|
612
|
-
* gt.formatDateTime(new Date(), { dateStyle: 'full', timeStyle: 'long' });
|
|
613
|
-
* // Returns: "Thursday, March 14, 2024 at 2:30:45 PM GMT-7"
|
|
614
|
-
*/
|
|
615
|
-
formatDateTime(date, options) {
|
|
616
|
-
return this.localeConfig.formatDateTime(date, this.targetLocale, options);
|
|
617
|
-
}
|
|
618
|
-
/**
|
|
619
|
-
* Formats a currency value according to the specified locales and options.
|
|
620
|
-
*
|
|
621
|
-
* @param {number} value - The currency value to format.
|
|
622
|
-
* @param {string} currency - The currency code (e.g., 'USD', 'EUR')
|
|
623
|
-
* @param {Object} [options] - Additional options for currency formatting.
|
|
624
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
625
|
-
* @param {Intl.NumberFormatOptions} [options] - Additional Intl.NumberFormat options.
|
|
626
|
-
* @returns {string} The formatted currency value.
|
|
627
|
-
*
|
|
628
|
-
* @example
|
|
629
|
-
* gt.formatCurrency(1234.56, 'USD', { style: 'currency' });
|
|
630
|
-
* // Returns: "$1,234.56"
|
|
631
|
-
*/
|
|
632
|
-
formatCurrency(value, currency, options) {
|
|
633
|
-
return this.localeConfig.formatCurrency(value, currency, this.targetLocale, options);
|
|
634
|
-
}
|
|
635
|
-
/**
|
|
636
|
-
* Formats a list of items according to the specified locales and options.
|
|
637
|
-
*
|
|
638
|
-
* @param {Array<string | number>} array - The list of items to format.
|
|
639
|
-
* @param {Object} [options] - Additional options for list formatting.
|
|
640
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
641
|
-
* @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.
|
|
642
|
-
* @returns {string} The formatted list.
|
|
643
|
-
*
|
|
644
|
-
* @example
|
|
645
|
-
* gt.formatList(['apple', 'banana', 'orange'], { type: 'conjunction' });
|
|
646
|
-
* // Returns: "apple, banana, and orange"
|
|
647
|
-
*/
|
|
648
|
-
formatList(array, options) {
|
|
649
|
-
return this.localeConfig.formatList(array, this.targetLocale, options);
|
|
650
|
-
}
|
|
651
|
-
/**
|
|
652
|
-
* Formats a list of items according to the specified locales and options.
|
|
653
|
-
* @param {Array<T>} array - The list of items to format.
|
|
654
|
-
* @param {Object} [options] - Additional options for list formatting.
|
|
655
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
656
|
-
* @param {Intl.ListFormatOptions} [options] - Additional Intl.ListFormat options.
|
|
657
|
-
* @returns {Array<T | string>} The formatted list parts.
|
|
658
|
-
*
|
|
659
|
-
* @example
|
|
660
|
-
* gt.formatListToParts(['apple', 42, { foo: 'bar' }], { type: 'conjunction', style: 'short', locales: ['en'] });
|
|
661
|
-
* // Returns: ['apple', ', ', 42, ' and ', '{ foo: "bar" }']
|
|
662
|
-
*/
|
|
663
|
-
formatListToParts(array, options) {
|
|
664
|
-
return this.localeConfig.formatListToParts(array, this.targetLocale, options);
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Formats a relative time value according to the specified locales and options.
|
|
668
|
-
*
|
|
669
|
-
* @param {number} value - The relative time value to format.
|
|
670
|
-
* @param {Intl.RelativeTimeFormatUnit} unit - The unit of time (e.g., 'second', 'minute', 'hour', 'day', 'week', 'month', 'year')
|
|
671
|
-
* @param {Object} options - Additional options for relative time formatting.
|
|
672
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
673
|
-
* @param {Intl.RelativeTimeFormatOptions} [options] - Additional Intl.RelativeTimeFormat options.
|
|
674
|
-
* @returns {string} The formatted relative time string.
|
|
675
|
-
*
|
|
676
|
-
* @example
|
|
677
|
-
* gt.formatRelativeTime(-1, 'day', { locales: ['en-US'], numeric: 'auto' });
|
|
678
|
-
* // Returns: "yesterday"
|
|
679
|
-
*/
|
|
680
|
-
formatRelativeTime(value, unit, options) {
|
|
681
|
-
return this.localeConfig.formatRelativeTime(value, unit, this.targetLocale, options);
|
|
682
|
-
}
|
|
683
|
-
/**
|
|
684
|
-
* Formats a relative time string from a Date, automatically selecting the best unit.
|
|
685
|
-
*
|
|
686
|
-
* @param {Date} date - The date to format relative to now.
|
|
687
|
-
* @param {Object} [options] - Additional options for relative time formatting.
|
|
688
|
-
* @param {string | string[]} [options.locales] - The locales to use for formatting.
|
|
689
|
-
* @returns {string} The formatted relative time string (e.g., "2 hours ago", "in 3 days")
|
|
690
|
-
*
|
|
691
|
-
* @example
|
|
692
|
-
* gt.formatRelativeTimeFromDate(new Date(Date.now() - 3600000));
|
|
693
|
-
* // Returns: "1 hour ago"
|
|
694
|
-
*/
|
|
695
|
-
formatRelativeTimeFromDate(date, options) {
|
|
696
|
-
return this.localeConfig.formatRelativeTimeFromDate(date, this.targetLocale, options);
|
|
697
|
-
}
|
|
698
|
-
/**
|
|
699
|
-
* Retrieves the display name of a locale code using Intl.DisplayNames, returning an empty string if no name is found.
|
|
700
|
-
*
|
|
701
|
-
* @param {string} [locale=this.targetLocale] - A BCP-47 locale code.
|
|
702
|
-
* @returns {string} The display name corresponding to the code.
|
|
703
|
-
* @throws {Error} If no target locale is provided.
|
|
704
|
-
*
|
|
705
|
-
* @example
|
|
706
|
-
* gt.getLocaleName('es-ES');
|
|
707
|
-
* // Returns: "Spanish (Spain)"
|
|
708
|
-
*/
|
|
709
|
-
getLocaleName(locale = this.targetLocale) {
|
|
710
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleName"));
|
|
711
|
-
return this.localeConfig.getLocaleName(locale);
|
|
712
|
-
}
|
|
713
|
-
/**
|
|
714
|
-
* Retrieves an emoji based on a given locale code.
|
|
715
|
-
* Uses the locale's region (if present) to select an emoji or falls back on default emojis.
|
|
716
|
-
*
|
|
717
|
-
* @param {string} [locale=this.targetLocale] - A BCP-47 locale code (e.g., 'en-US', 'fr-CA')
|
|
718
|
-
* @returns {string} The emoji representing the locale or its region.
|
|
719
|
-
* @throws {Error} If no target locale is provided.
|
|
720
|
-
*
|
|
721
|
-
* @example
|
|
722
|
-
* gt.getLocaleEmoji('es-ES');
|
|
723
|
-
* // Returns: "🇪🇸"
|
|
724
|
-
*/
|
|
725
|
-
getLocaleEmoji(locale = this.targetLocale) {
|
|
726
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleEmoji"));
|
|
727
|
-
return this.localeConfig.getLocaleEmoji(locale);
|
|
728
|
-
}
|
|
729
|
-
/**
|
|
730
|
-
* Generates linguistic details for a given locale code.
|
|
731
|
-
*
|
|
732
|
-
* This function returns information about the locale,
|
|
733
|
-
* script, and region of a given language code both in a standard form and in a maximized form (with likely script and region).
|
|
734
|
-
* The function provides these names in both your default language and native forms, and an associated emoji.
|
|
735
|
-
*
|
|
736
|
-
* @param {string} [locale=this.targetLocale] - The locale code to get properties for (e.g., "de-AT").
|
|
737
|
-
* @returns {LocaleProperties} - An object containing detailed information about the locale.
|
|
738
|
-
*
|
|
739
|
-
* @property {string} code - The full locale code, e.g., "de-AT".
|
|
740
|
-
* @property {string} name - Language name in the default display language, e.g., "Austrian German".
|
|
741
|
-
* @property {string} nativeName - Language name in the locale's native language, e.g., "Österreichisches Deutsch".
|
|
742
|
-
* @property {string} languageCode - The base language code, e.g., "de".
|
|
743
|
-
* @property {string} languageName - The language name in the default display language, e.g., "German".
|
|
744
|
-
* @property {string} nativeLanguageName - The language name in the native language, e.g., "Deutsch".
|
|
745
|
-
* @property {string} nameWithRegionCode - Language name with region in the default language, e.g., "German (AT)".
|
|
746
|
-
* @property {string} nativeNameWithRegionCode - Language name with region in the native language, e.g., "Deutsch (AT)".
|
|
747
|
-
* @property {string} regionCode - The region code from maximization, e.g., "AT".
|
|
748
|
-
* @property {string} regionName - The region name in the default display language, e.g., "Austria".
|
|
749
|
-
* @property {string} nativeRegionName - The region name in the native language, e.g., "Österreich".
|
|
750
|
-
* @property {string} scriptCode - The script code from maximization, e.g., "Latn".
|
|
751
|
-
* @property {string} scriptName - The script name in the default display language, e.g., "Latin".
|
|
752
|
-
* @property {string} nativeScriptName - The script name in the native language, e.g., "Lateinisch".
|
|
753
|
-
* @property {string} maximizedCode - The maximized locale code, e.g., "de-Latn-AT".
|
|
754
|
-
* @property {string} maximizedName - Maximized locale name with likely script in the default language, e.g., "Austrian German (Latin)".
|
|
755
|
-
* @property {string} nativeMaximizedName - Maximized locale name in the native language, e.g., "Österreichisches Deutsch (Lateinisch)".
|
|
756
|
-
* @property {string} minimizedCode - Minimized locale code, e.g., "de-AT" (or "de" for "de-DE").
|
|
757
|
-
* @property {string} minimizedName - Minimized language name in the default language, e.g., "Austrian German".
|
|
758
|
-
* @property {string} nativeMinimizedName - Minimized language name in the native language, e.g., "Österreichisches Deutsch".
|
|
759
|
-
* @property {string} emoji - The emoji associated with the locale's region, if applicable.
|
|
760
|
-
*/
|
|
761
|
-
getLocaleProperties(locale = this.targetLocale) {
|
|
762
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleProperties"));
|
|
763
|
-
return this.localeConfig.getLocaleProperties(locale);
|
|
764
|
-
}
|
|
765
|
-
/**
|
|
766
|
-
* Retrieves multiple properties for a given region code, including:
|
|
767
|
-
* - `code`: the original region code
|
|
768
|
-
* - `name`: the localized display name
|
|
769
|
-
* - `emoji`: the associated flag or symbol
|
|
770
|
-
*
|
|
771
|
-
* Behavior:
|
|
772
|
-
* - Accepts ISO 3166-1 alpha-2 or UN M.49 region codes (e.g., `"US"`, `"FR"`, `"419"`).
|
|
773
|
-
* - Uses the instance's `targetLocale` to localize the region name for the user.
|
|
774
|
-
* - If `customMapping` contains a `name` or `emoji` for the region, those override the default values.
|
|
775
|
-
* - Otherwise, uses `Intl.DisplayNames` to get the localized region name, falling back to `libraryDefaultLocale`.
|
|
776
|
-
* - Falls back to the region code as `name` if display name resolution fails.
|
|
777
|
-
* - Falls back to a default emoji if no emoji mapping is found in built-in data or `customMapping`.
|
|
778
|
-
*
|
|
779
|
-
* @param {string} [region=this.getLocaleProperties().regionCode] - The region code to look up (e.g., `"US"`, `"GB"`, `"DE"`).
|
|
780
|
-
* @param {CustomRegionMapping} [customMapping] - Optional mapping of region codes to custom names and/or emojis.
|
|
781
|
-
* @returns {{ code: string, name: string, emoji: string }} An object containing:
|
|
782
|
-
* - `code`: the input region code
|
|
783
|
-
* - `name`: the localized or custom region name
|
|
784
|
-
* - `emoji`: the matching emoji flag or symbol
|
|
785
|
-
*
|
|
786
|
-
* @throws {Error} If no target locale is available to determine region properties.
|
|
787
|
-
*
|
|
788
|
-
* @example
|
|
789
|
-
* const gt = new GTRuntime({ targetLocale: 'en-US' });
|
|
790
|
-
* gt.getRegionProperties('US');
|
|
791
|
-
* // => { code: 'US', name: 'United States', emoji: '🇺🇸' }
|
|
792
|
-
*
|
|
793
|
-
* @example
|
|
794
|
-
* const gt = new GTRuntime({ targetLocale: 'fr-FR' });
|
|
795
|
-
* gt.getRegionProperties('US');
|
|
796
|
-
* // => { code: 'US', name: 'États-Unis', emoji: '🇺🇸' }
|
|
797
|
-
*
|
|
798
|
-
* @example
|
|
799
|
-
* gt.getRegionProperties('US', { US: { name: 'USA', emoji: '🗽' } });
|
|
800
|
-
* // => { code: 'US', name: 'USA', emoji: '🗽' }
|
|
801
|
-
*/
|
|
802
|
-
getRegionProperties(region = this.getLocaleProperties().regionCode, customMapping) {
|
|
803
|
-
if (!customMapping) {
|
|
804
|
-
if (this.customMapping && !this.customRegionMapping) {
|
|
805
|
-
const customRegionMapping = {};
|
|
806
|
-
for (const [locale, lp] of Object.entries(this.customMapping)) if (lp && typeof lp === "object" && lp.regionCode && !customRegionMapping[lp.regionCode]) {
|
|
807
|
-
const { regionName: name, emoji } = lp;
|
|
808
|
-
customRegionMapping[lp.regionCode] = {
|
|
809
|
-
locale,
|
|
810
|
-
...name && { name },
|
|
811
|
-
...emoji && { emoji }
|
|
812
|
-
};
|
|
813
|
-
}
|
|
814
|
-
this.customRegionMapping = customRegionMapping;
|
|
815
|
-
}
|
|
816
|
-
customMapping = this.customRegionMapping;
|
|
817
|
-
}
|
|
818
|
-
return getRegionProperties(region, this.targetLocale, customMapping);
|
|
819
|
-
}
|
|
820
|
-
/**
|
|
821
|
-
* Determines whether a translation is required based on the source and target locales.
|
|
822
|
-
*
|
|
823
|
-
* @param {string} [sourceLocale=this.sourceLocale] - The locale code for the original content.
|
|
824
|
-
* @param {string} [targetLocale=this.targetLocale] - The locale code to translate into.
|
|
825
|
-
* @param {string[]} [approvedLocales=this.locales] - Optional array of approved target locales.
|
|
826
|
-
* @returns {boolean} True if translation is required, false otherwise
|
|
827
|
-
* @throws {Error} If no source locale is provided.
|
|
828
|
-
* @throws {Error} If no target locale is provided.
|
|
829
|
-
*
|
|
830
|
-
* @example
|
|
831
|
-
* gt.requiresTranslation('en-US', 'es-ES');
|
|
832
|
-
* // Returns: true
|
|
833
|
-
*/
|
|
834
|
-
requiresTranslation(sourceLocale = this.sourceLocale, targetLocale = this.targetLocale, approvedLocales = this.locales, customMapping = this.customMapping) {
|
|
835
|
-
if (!sourceLocale) throw new Error(noSourceLocaleProvidedError("requiresTranslation"));
|
|
836
|
-
if (!targetLocale) throw new Error(noTargetLocaleProvidedError("requiresTranslation"));
|
|
837
|
-
if (customMapping === this.customMapping) return this.localeConfig.requiresTranslation(targetLocale, sourceLocale, approvedLocales);
|
|
838
|
-
return requiresTranslation(sourceLocale, targetLocale, approvedLocales, customMapping);
|
|
839
|
-
}
|
|
840
|
-
/**
|
|
841
|
-
* Determines the best matching locale from the provided approved locales list.
|
|
842
|
-
*
|
|
843
|
-
* @param {string | string[]} locales - A single locale or array of locales in preference order.
|
|
844
|
-
* @param {string[]} [approvedLocales=this.locales] - Array of approved locales in preference order.
|
|
845
|
-
* @returns {string | undefined} The best matching locale, or undefined if no match is found.
|
|
846
|
-
*
|
|
847
|
-
* @example
|
|
848
|
-
* gt.determineLocale(['fr-CA', 'fr-FR'], ['en-US', 'fr-FR', 'es-ES']);
|
|
849
|
-
* // Returns: "fr-FR"
|
|
850
|
-
*/
|
|
851
|
-
determineLocale(locales, approvedLocales = this.locales || [], customMapping = this.customMapping) {
|
|
852
|
-
if (customMapping === this.customMapping) return this.localeConfig.determineLocale(locales, approvedLocales ?? []);
|
|
853
|
-
return new LocaleConfig({ customMapping }).determineLocale(locales, approvedLocales ?? []);
|
|
854
|
-
}
|
|
855
|
-
/**
|
|
856
|
-
* Gets the text direction for a given locale code.
|
|
857
|
-
*
|
|
858
|
-
* @param {string} [locale=this.targetLocale] - A BCP-47 locale code.
|
|
859
|
-
* @returns {'ltr' | 'rtl'} 'rtl' if the locale is right-to-left; otherwise 'ltr'.
|
|
860
|
-
* @throws {Error} If no target locale is provided.
|
|
861
|
-
*
|
|
862
|
-
* @example
|
|
863
|
-
* gt.getLocaleDirection('ar-SA');
|
|
864
|
-
* // Returns: "rtl"
|
|
865
|
-
*/
|
|
866
|
-
getLocaleDirection(locale = this.targetLocale) {
|
|
867
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("getLocaleDirection"));
|
|
868
|
-
return this.localeConfig.getLocaleDirection(locale);
|
|
869
|
-
}
|
|
870
|
-
/**
|
|
871
|
-
* Checks if a given BCP 47 locale code is valid.
|
|
872
|
-
*
|
|
873
|
-
* @param {string} [locale=this.targetLocale] - The BCP 47 locale code to validate.
|
|
874
|
-
* @param {CustomMapping} [customMapping=this.customMapping] - The custom mapping to use for validation.
|
|
875
|
-
* @returns {boolean} True if the locale code is valid, false otherwise
|
|
876
|
-
* @throws {Error} If no target locale is provided.
|
|
877
|
-
*
|
|
878
|
-
* @example
|
|
879
|
-
* gt.isValidLocale('en-US');
|
|
880
|
-
* // Returns: true
|
|
881
|
-
*/
|
|
882
|
-
isValidLocale(locale = this.targetLocale, customMapping = this.customMapping) {
|
|
883
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("isValidLocale"));
|
|
884
|
-
if (customMapping === this.customMapping) return this.localeConfig.isValidLocale(locale);
|
|
885
|
-
return isValidLocale(locale, customMapping);
|
|
886
|
-
}
|
|
887
|
-
/**
|
|
888
|
-
* Resolves the canonical locale for a given locale.
|
|
889
|
-
* @param locale - The locale to resolve the canonical locale for
|
|
890
|
-
* @param customMapping - The custom mapping to use for resolving the canonical locale
|
|
891
|
-
* @returns The canonical locale, or the input locale when no canonical mapping exists.
|
|
892
|
-
*/
|
|
893
|
-
resolveCanonicalLocale(locale = this.targetLocale, customMapping = this.customMapping) {
|
|
894
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("resolveCanonicalLocale"));
|
|
895
|
-
if (customMapping === this.customMapping) return this.localeConfig.resolveCanonicalLocale(locale);
|
|
896
|
-
return resolveCanonicalLocale(locale, customMapping);
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
|
-
* Resolves the alias locale for a given locale.
|
|
900
|
-
* @param locale - The locale to resolve the alias locale for
|
|
901
|
-
* @param customMapping - The custom mapping to use for resolving the alias locale
|
|
902
|
-
* @returns The configured alias for a canonical locale, or the input locale when already an alias or no alias mapping exists.
|
|
903
|
-
*/
|
|
904
|
-
resolveAliasLocale(locale, customMapping = this.customMapping) {
|
|
905
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("resolveAliasLocale"));
|
|
906
|
-
if (customMapping === this.customMapping) return this.localeConfig.resolveAliasLocale(locale);
|
|
907
|
-
return resolveAliasLocale(locale, customMapping);
|
|
908
|
-
}
|
|
909
|
-
/**
|
|
910
|
-
* Standardizes a BCP 47 locale code to ensure correct formatting.
|
|
911
|
-
*
|
|
912
|
-
* @param {string} [locale=this.targetLocale] - The BCP 47 locale code to standardize.
|
|
913
|
-
* @returns {string} The standardized locale code, or the input string if it cannot be standardized.
|
|
914
|
-
* @throws {Error} If no target locale is provided.
|
|
915
|
-
*
|
|
916
|
-
* @example
|
|
917
|
-
* gt.standardizeLocale('en_us');
|
|
918
|
-
* // Returns: "en-US"
|
|
919
|
-
*/
|
|
920
|
-
standardizeLocale(locale = this.targetLocale) {
|
|
921
|
-
if (!locale) throw new Error(noTargetLocaleProvidedError("standardizeLocale"));
|
|
922
|
-
return this.localeConfig.standardizeLocale(locale);
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Checks if multiple BCP 47 locale codes represent the same dialect.
|
|
926
|
-
*
|
|
927
|
-
* @param {...(string | string[])} locales - The BCP 47 locale codes to compare.
|
|
928
|
-
* @returns {boolean} True if all codes represent the same dialect, false otherwise
|
|
929
|
-
*
|
|
930
|
-
* @example
|
|
931
|
-
* gt.isSameDialect('en-US', 'en-GB');
|
|
932
|
-
* // Returns: false
|
|
933
|
-
*
|
|
934
|
-
* gt.isSameDialect('en', 'en-US');
|
|
935
|
-
* // Returns: true
|
|
936
|
-
*/
|
|
937
|
-
isSameDialect(...locales) {
|
|
938
|
-
return this.localeConfig.isSameDialect(...locales);
|
|
939
|
-
}
|
|
940
|
-
/**
|
|
941
|
-
* Checks if multiple BCP 47 locale codes represent the same language.
|
|
942
|
-
*
|
|
943
|
-
* @param {...(string | string[])} locales - The BCP 47 locale codes to compare.
|
|
944
|
-
* @returns {boolean} True if all codes represent the same language, false otherwise
|
|
945
|
-
*
|
|
946
|
-
* @example
|
|
947
|
-
* gt.isSameLanguage('en-US', 'en-GB');
|
|
948
|
-
* // Returns: true
|
|
949
|
-
*/
|
|
950
|
-
isSameLanguage(...locales) {
|
|
951
|
-
return this.localeConfig.isSameLanguage(...locales);
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Checks if a locale is a superset of another locale.
|
|
955
|
-
*
|
|
956
|
-
* @param {string} superLocale - The locale to check if it is a superset
|
|
957
|
-
* @param {string} subLocale - The locale to check if it is a subset
|
|
958
|
-
* @returns {boolean} True if superLocale is a superset of subLocale, false otherwise
|
|
959
|
-
*
|
|
960
|
-
* @example
|
|
961
|
-
* gt.isSupersetLocale('en', 'en-US');
|
|
962
|
-
* // Returns: true
|
|
963
|
-
*
|
|
964
|
-
* gt.isSupersetLocale('en-US', 'en');
|
|
965
|
-
* // Returns: false
|
|
966
|
-
*/
|
|
967
|
-
isSupersetLocale(superLocale, subLocale) {
|
|
968
|
-
return this.localeConfig.isSupersetLocale(superLocale, subLocale);
|
|
969
|
-
}
|
|
970
|
-
};
|
|
971
|
-
//#endregion
|
|
972
|
-
export { gtInstanceLogger as a, translationRequestFailedError as c, fetchLogger as i, translationTimeoutError as l, validateResponse as n, noSourceLocaleProvidedError as o, fetchWithTimeout as r, noTargetLocaleProvidedError as s, GTRuntime as t };
|
|
973
|
-
|
|
974
|
-
//# sourceMappingURL=runtime-Bcp4F2ME.mjs.map
|