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.
Files changed (153) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +2 -1
  3. package/dist/{ApiError-BcjcnTAr.cjs → ApiError-BCjEo_CM.cjs} +1 -1
  4. package/dist/{ApiError-BcjcnTAr.cjs.map → ApiError-BCjEo_CM.cjs.map} +1 -1
  5. package/dist/{ApiError-CUKcz3YS.mjs → ApiError-DxWKM0Xt.mjs} +1 -1
  6. package/dist/{ApiError-CUKcz3YS.mjs.map → ApiError-DxWKM0Xt.mjs.map} +1 -1
  7. package/dist/adapter/createGtApi.d.ts +196 -27
  8. package/dist/adapter/createGtApi.js +561 -117
  9. package/dist/adapter/modelProvider.d.ts +4 -0
  10. package/dist/adapter/modelProvider.js +6 -0
  11. package/dist/derive-Cv5_y8Tf.mjs +656 -0
  12. package/dist/derive-Cv5_y8Tf.mjs.map +1 -0
  13. package/dist/{derive-DBCCXTmL.d.cts → derive-J2NQLqZm.d.cts} +1 -1
  14. package/dist/derive-t_E3ftJN.cjs +733 -0
  15. package/dist/derive-t_E3ftJN.cjs.map +1 -0
  16. package/dist/diagnostics-CqAHg_Vc.d.cts +34 -0
  17. package/dist/diagnostics-DKA2SkZB.mjs +45 -0
  18. package/dist/diagnostics-DKA2SkZB.mjs.map +1 -0
  19. package/dist/{unwrapApiResult-BzGfPw75.mjs → diagnostics-DKtiPUvo.cjs} +12 -31
  20. package/dist/diagnostics-DKtiPUvo.cjs.map +1 -0
  21. package/dist/diagnostics-DYtVjOm5.d.mts +34 -0
  22. package/dist/diagnostics.cjs +4 -0
  23. package/dist/diagnostics.d.cts +2 -0
  24. package/dist/diagnostics.d.mts +2 -0
  25. package/dist/diagnostics.d.ts +1 -0
  26. package/dist/diagnostics.js +1 -0
  27. package/dist/diagnostics.mjs +2 -0
  28. package/dist/errors.cjs +1 -1
  29. package/dist/errors.mjs +1 -1
  30. package/dist/file-B37WkCqM.cjs.map +1 -1
  31. package/dist/file-Dga6cyM8.mjs.map +1 -1
  32. package/dist/{id-X2zyx5Jk.mjs → id-B2wA7-S-.mjs} +19 -3
  33. package/dist/id-B2wA7-S-.mjs.map +1 -0
  34. package/dist/{id-pdr3R1xs.cjs → id-DJ_59q21.cjs} +25 -3
  35. package/dist/id-DJ_59q21.cjs.map +1 -0
  36. package/dist/id.cjs +1 -1
  37. package/dist/id.d.cts +1 -1
  38. package/dist/id.d.mts +1 -1
  39. package/dist/id.mjs +1 -1
  40. package/dist/index.cjs +94 -753
  41. package/dist/index.cjs.map +1 -1
  42. package/dist/index.d.cts +14 -33
  43. package/dist/index.d.mts +13 -32
  44. package/dist/index.d.ts +20 -16
  45. package/dist/index.js +110 -98
  46. package/dist/index.mjs +88 -746
  47. package/dist/index.mjs.map +1 -1
  48. package/dist/internal.cjs +16 -186
  49. package/dist/internal.cjs.map +1 -1
  50. package/dist/internal.d.cts +200 -62
  51. package/dist/internal.d.mts +199 -61
  52. package/dist/internal.d.ts +3 -1
  53. package/dist/internal.js +2 -1
  54. package/dist/internal.mjs +6 -178
  55. package/dist/internal.mjs.map +1 -1
  56. package/dist/logging/errors.d.ts +0 -1
  57. package/dist/logging/errors.js +0 -6
  58. package/dist/logging/logger.js +6 -4
  59. package/dist/openapi.json +2344 -845
  60. package/dist/runtime.cjs +580 -2
  61. package/dist/runtime.cjs.map +1 -0
  62. package/dist/runtime.d.cts +12 -6
  63. package/dist/runtime.d.mts +12 -6
  64. package/dist/runtime.d.ts +10 -4
  65. package/dist/runtime.js +10 -65
  66. package/dist/runtime.mjs +579 -1
  67. package/dist/runtime.mjs.map +1 -0
  68. package/dist/runtimeTranslate-CVw143pQ.mjs +506 -0
  69. package/dist/runtimeTranslate-CVw143pQ.mjs.map +1 -0
  70. package/dist/runtimeTranslate-DJioRjb6.cjs +601 -0
  71. package/dist/runtimeTranslate-DJioRjb6.cjs.map +1 -0
  72. package/dist/translate/awaitJobs.d.ts +2 -2
  73. package/dist/translate/awaitJobs.js +1 -156
  74. package/dist/translate/checkJobStatus.d.ts +2 -1
  75. package/dist/translate/checkJobStatus.js +1 -55
  76. package/dist/translate/createBranch.d.ts +2 -6
  77. package/dist/translate/createBranch.js +1 -53
  78. package/dist/translate/enqueueFiles.js +1 -95
  79. package/dist/translate/getProjectInfo.d.ts +2 -6
  80. package/dist/translate/getProjectInfo.js +1 -54
  81. package/dist/translate/processFileMoves.d.ts +3 -13
  82. package/dist/translate/processFileMoves.js +1 -90
  83. package/dist/translate/publishFiles.d.ts +3 -15
  84. package/dist/translate/publishFiles.js +1 -56
  85. package/dist/translate/queryBranchData.js +1 -53
  86. package/dist/translate/queryFileData.d.ts +3 -41
  87. package/dist/translate/queryFileData.js +1 -71
  88. package/dist/translate/runtimeTranslate.d.ts +6 -0
  89. package/dist/translate/runtimeTranslate.js +297 -0
  90. package/dist/translate/setupProject.d.ts +2 -6
  91. package/dist/translate/setupProject.js +1 -63
  92. package/dist/translate/submitUserEditDiffs.js +1 -68
  93. package/dist/translate/utils/fetchWithTimeout.js +19 -12
  94. package/dist/{types-bCr8pV1Z.d.cts → types-Si4UstLL.d.mts} +41 -165
  95. package/dist/types-dir/__tests__/runtimeTranslate.type-test.js +18 -0
  96. package/dist/types-dir/api/branch.d.ts +3 -9
  97. package/dist/types-dir/api/checkFileTranslations.d.ts +2 -22
  98. package/dist/types-dir/api/downloadFileBatch.d.ts +2 -7
  99. package/dist/types-dir/api/entry.d.ts +3 -8
  100. package/dist/types-dir/api/file.d.ts +2 -1
  101. package/dist/types-dir/api/json.d.ts +1 -4
  102. package/dist/types-dir/api/project.d.ts +2 -7
  103. package/dist/types-dir/api/uploadAssets.d.ts +3 -10
  104. package/dist/types-dir/api/uploadAssets.js +0 -4
  105. package/dist/types-dir/config.d.ts +1 -0
  106. package/dist/{types-Dp1drjxq.d.mts → types-yByDbKnV.d.cts} +41 -165
  107. package/dist/types.d.cts +2 -2
  108. package/dist/types.d.mts +2 -2
  109. package/dist/types.d.ts +26 -7
  110. package/package.json +15 -2
  111. package/dist/derive-2CDqwrvS.cjs +0 -303
  112. package/dist/derive-2CDqwrvS.cjs.map +0 -1
  113. package/dist/derive-CTzR56T_.mjs +0 -233
  114. package/dist/derive-CTzR56T_.mjs.map +0 -1
  115. package/dist/id-X2zyx5Jk.mjs.map +0 -1
  116. package/dist/id-pdr3R1xs.cjs.map +0 -1
  117. package/dist/isVariable-8-Wy5FnX.mjs +0 -20
  118. package/dist/isVariable-8-Wy5FnX.mjs.map +0 -1
  119. package/dist/isVariable-I3nllgeI.cjs +0 -25
  120. package/dist/isVariable-I3nllgeI.cjs.map +0 -1
  121. package/dist/projects/getProjectData.js +0 -87
  122. package/dist/runtime-Bcp4F2ME.mjs +0 -974
  123. package/dist/runtime-Bcp4F2ME.mjs.map +0 -1
  124. package/dist/runtime-C25lwh9m.cjs +0 -1027
  125. package/dist/runtime-C25lwh9m.cjs.map +0 -1
  126. package/dist/translate/api.d.ts +0 -4
  127. package/dist/translate/api.js +0 -4
  128. package/dist/translate/createTag.d.ts +0 -19
  129. package/dist/translate/createTag.js +0 -67
  130. package/dist/translate/downloadFileBatch.d.ts +0 -1
  131. package/dist/translate/downloadFileBatch.js +0 -80
  132. package/dist/translate/getOrphanedFiles.d.ts +0 -8
  133. package/dist/translate/getOrphanedFiles.js +0 -97
  134. package/dist/translate/querySourceFile.d.ts +0 -1
  135. package/dist/translate/querySourceFile.js +0 -67
  136. package/dist/translate/translateMany.d.ts +0 -1
  137. package/dist/translate/translateMany.js +0 -124
  138. package/dist/translate/uploadFonts.d.ts +0 -1
  139. package/dist/translate/uploadFonts.js +0 -74
  140. package/dist/translate/uploadSourceFiles.d.ts +0 -1
  141. package/dist/translate/uploadSourceFiles.js +0 -90
  142. package/dist/translate/uploadTranslations.d.ts +0 -1
  143. package/dist/translate/uploadTranslations.js +0 -106
  144. package/dist/translate/utils/apiRequest.d.ts +0 -1
  145. package/dist/translate/utils/apiRequest.js +0 -167
  146. package/dist/translate/utils/generateRequestHeaders.d.ts +0 -2
  147. package/dist/translate/utils/generateRequestHeaders.js +0 -21
  148. package/dist/translate/utils/handleFetchError.d.ts +0 -1
  149. package/dist/translate/utils/handleFetchError.js +0 -12
  150. package/dist/unwrapApiResult-BzGfPw75.mjs.map +0 -1
  151. package/dist/unwrapApiResult-Dv6Mfw_K.cjs +0 -134
  152. package/dist/unwrapApiResult-Dv6Mfw_K.cjs.map +0 -1
  153. /package/dist/{projects/getProjectData.d.ts → types-dir/__tests__/runtimeTranslate.type-test.d.ts} +0 -0
@@ -0,0 +1,4 @@
1
+ import { ModelProvider } from '@generaltranslation/api';
2
+ export type { ModelProvider };
3
+ export declare const supportedModelProviders: ("ANTHROPIC" | "OPENAI" | "XAI" | "GOOGLE")[];
4
+ export declare function isModelProvider(value: unknown): value is ModelProvider;
@@ -0,0 +1,6 @@
1
+ import { ModelProvider } from '@generaltranslation/api';
2
+ export var supportedModelProviders =
3
+ /* @__PURE__ */ Object.values(ModelProvider);
4
+ export function isModelProvider(value) {
5
+ return supportedModelProviders.includes(value);
6
+ }
@@ -0,0 +1,656 @@
1
+ import { a as unwrapApiResult, n as translateMany, o as isModelProvider, s as supportedModelProviders, t as translate$1 } from "./runtimeTranslate-CVw143pQ.mjs";
2
+ import { t as createDiagnosticMessage } from "./diagnostics-DKA2SkZB.mjs";
3
+ import { n as isBinaryFileFormat } from "./file-Dga6cyM8.mjs";
4
+ import { DEFAULT_BATCH_SIZE, createApiClient, createBranch, createProject, createProjectApiKey, createTag, downloadFiles, enqueueFileTranslations, generateProjectContext, getBranchInfo, getFileInfo, getOrphanedFiles, getProjectInfo, getTranslationJobInfo, getTranslationStatus, listOrgs, listProjects, pollJobs, processBatches, processFileMoves, publishFiles, submitUserEditDiffs, uploadAssets, uploadSourceFiles, uploadTranslations } from "@generaltranslation/api";
5
+ import { resolveAliasLocale, resolveCanonicalLocale, standardizeLocale } from "@generaltranslation/format";
6
+ import { TYPE, parse } from "@generaltranslation/icu";
7
+ //#region src/utils/base64.ts
8
+ function encode(data) {
9
+ if (typeof Buffer !== "undefined") return Buffer.from(data, "utf8").toString("base64");
10
+ const bytes = new TextEncoder().encode(data);
11
+ let binary = "";
12
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
13
+ return btoa(binary);
14
+ }
15
+ function decode(base64) {
16
+ if (typeof Buffer !== "undefined") return Buffer.from(base64, "base64").toString("utf8");
17
+ const binary = atob(base64);
18
+ const bytes = new Uint8Array(binary.length);
19
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
20
+ return new TextDecoder().decode(bytes);
21
+ }
22
+ function encodeFileContent(content, fileFormat) {
23
+ return isBinaryFileFormat(fileFormat) ? content : encode(content);
24
+ }
25
+ function decodeFileContent(content, fileFormat) {
26
+ return isBinaryFileFormat(fileFormat) ? content : decode(content);
27
+ }
28
+ //#endregion
29
+ //#region src/utils/isSupportedFileFormatTransform.ts
30
+ const SUPPORTED_TRANSFORMATIONS = {
31
+ GTJSON: ["GTJSON"],
32
+ JSON: ["JSON"],
33
+ PO: ["PO"],
34
+ POT: ["POT", "PO"],
35
+ YAML: ["YAML"],
36
+ MDX: ["MDX"],
37
+ MD: ["MD"],
38
+ TS: ["TS"],
39
+ JS: ["JS"],
40
+ HTML: ["HTML"],
41
+ TXT: ["TXT"],
42
+ TWILIO_CONTENT_JSON: ["TWILIO_CONTENT_JSON"],
43
+ LOTTIE: ["LOTTIE"],
44
+ SVG: ["SVG"],
45
+ DOT_STRINGS: ["DOT_STRINGS"],
46
+ DOT_STRINGSDICT: ["DOT_STRINGSDICT"],
47
+ ANDROID_STRINGS: ["ANDROID_STRINGS"],
48
+ XCSTRINGS: ["XCSTRINGS"]
49
+ };
50
+ /**
51
+ * This function checks if a file format transformation is supported during translation
52
+ * @param from - The source file format.
53
+ * @param to - The target file format.
54
+ * @returns True if the transformation is supported, false otherwise
55
+ */
56
+ function isSupportedFileFormatTransform(from, to) {
57
+ return SUPPORTED_TRANSFORMATIONS[from]?.includes(to) ?? false;
58
+ }
59
+ //#endregion
60
+ //#region src/translate/utils/validateFileFormatTransform.ts
61
+ /**
62
+ * Returns a user-facing validation error when a requested file format transform
63
+ * is missing source format context or is not currently supported.
64
+ */
65
+ function getFileFormatTransformError(file) {
66
+ if (!file.transformFormat) return void 0;
67
+ const fileLabel = file.fileName ?? file.fileId ?? "unknown file";
68
+ if (!file.fileFormat) return `fileFormat is required when transformFormat is provided for ${fileLabel}`;
69
+ if (!isSupportedFileFormatTransform(file.fileFormat, file.transformFormat)) return `Unsupported file format transform: ${file.fileFormat} -> ${file.transformFormat}`;
70
+ }
71
+ /**
72
+ * Validates file format transforms before sending upload/enqueue requests.
73
+ */
74
+ function validateFileFormatTransforms(files) {
75
+ for (const file of files) {
76
+ const error = getFileFormatTransformError(file);
77
+ if (error) throw new Error(error);
78
+ }
79
+ }
80
+ //#endregion
81
+ //#region src/adapter/createGtApi.ts
82
+ async function collectPages(loadPage) {
83
+ const items = [];
84
+ let cursor;
85
+ do {
86
+ const page = await loadPage(cursor);
87
+ items.push(...page.items);
88
+ cursor = page.nextCursor ?? void 0;
89
+ } while (cursor);
90
+ return items;
91
+ }
92
+ function normalizeJobStatus(job) {
93
+ return {
94
+ jobId: job.jobId,
95
+ status: job.status,
96
+ ...job.status === "failed" ? { error: { message: job.error.message ?? "" } } : {}
97
+ };
98
+ }
99
+ function createGtApiAdapter(defaultConfig) {
100
+ let client;
101
+ let config;
102
+ function resolveServiceLocale(locale) {
103
+ return standardizeLocale(resolveCanonicalLocale(locale, config?.customMapping));
104
+ }
105
+ function aliasUploadedFileLocale(file) {
106
+ return file.locale ? {
107
+ ...file,
108
+ locale: resolveAliasLocale(file.locale, config?.customMapping)
109
+ } : file;
110
+ }
111
+ function getConfig() {
112
+ if (!config) throw new Error("API client not configured — call configureApiClient first");
113
+ return config;
114
+ }
115
+ function getClient(timeoutMs) {
116
+ if (timeoutMs === void 0 && client) return client;
117
+ return createApiClient({
118
+ ...getConfig(),
119
+ timeoutMs
120
+ });
121
+ }
122
+ function configure(nextConfig) {
123
+ client = createApiClient(nextConfig);
124
+ config = { ...nextConfig };
125
+ }
126
+ async function translate(source, options, timeoutMs) {
127
+ return translate$1(source, options, {
128
+ ...getConfig(),
129
+ ...timeoutMs !== void 0 && { timeoutMs }
130
+ });
131
+ }
132
+ async function translateMany$1(sources, options, timeoutMs) {
133
+ return translateMany(sources, options, {
134
+ ...getConfig(),
135
+ ...timeoutMs !== void 0 && { timeoutMs }
136
+ });
137
+ }
138
+ if (defaultConfig) configure(defaultConfig);
139
+ async function loadJobStatuses(jobIds, options = {}) {
140
+ return unwrapApiResult(await getTranslationJobInfo({
141
+ body: { jobIds: [...jobIds] },
142
+ client: getClient(options.timeoutMs),
143
+ signal: options.signal
144
+ }));
145
+ }
146
+ async function loadProjectInfo(projectId, timeoutMs) {
147
+ const resolvedProjectId = projectId ?? getConfig().projectId;
148
+ if (!resolvedProjectId) throw new Error("Project ID is required to fetch project information");
149
+ return unwrapApiResult(await getProjectInfo({
150
+ client: getClient(timeoutMs),
151
+ path: { projectId: resolvedProjectId }
152
+ }));
153
+ }
154
+ return {
155
+ configure,
156
+ getClient,
157
+ resolveAliasLocale(locale) {
158
+ return resolveAliasLocale(locale, config?.customMapping);
159
+ },
160
+ resolveCanonicalLocale(locale) {
161
+ return resolveServiceLocale(locale);
162
+ },
163
+ translate,
164
+ translateMany: translateMany$1,
165
+ async queryBranchData(body) {
166
+ return unwrapApiResult(await getBranchInfo({
167
+ body,
168
+ client: getClient()
169
+ }));
170
+ },
171
+ async createBranch(body) {
172
+ return unwrapApiResult(await createBranch({
173
+ body,
174
+ client: getClient()
175
+ }));
176
+ },
177
+ async processFileMoves(moves, options = {}) {
178
+ const results = await processBatches(moves, async (batch) => {
179
+ return unwrapApiResult(await processFileMoves({
180
+ body: {
181
+ branchId: options.branchId,
182
+ moves: batch
183
+ },
184
+ client: getClient(options.timeout)
185
+ })).results;
186
+ });
187
+ const succeeded = results.filter(({ success }) => success).length;
188
+ return {
189
+ results,
190
+ summary: {
191
+ total: moves.length,
192
+ succeeded,
193
+ failed: results.length - succeeded
194
+ }
195
+ };
196
+ },
197
+ async getOrphanedFiles(branchId, fileIds, options = {}) {
198
+ const request = async (batch) => unwrapApiResult(await getOrphanedFiles({
199
+ body: {
200
+ branchId,
201
+ fileIds: batch
202
+ },
203
+ client: getClient(options.timeout)
204
+ }));
205
+ if (fileIds.length === 0) return request([]);
206
+ const results = await processBatches(fileIds, async (batch) => [await request(batch)]);
207
+ const orphanedFiles = new Map(results[0].orphanedFiles.map((file) => [file.fileId, file]));
208
+ for (const result of results.slice(1)) {
209
+ const batchFileIds = new Set(result.orphanedFiles.map((file) => file.fileId));
210
+ for (const fileId of Array.from(orphanedFiles.keys())) if (!batchFileIds.has(fileId)) orphanedFiles.delete(fileId);
211
+ }
212
+ return { orphanedFiles: Array.from(orphanedFiles.values()) };
213
+ },
214
+ async setupProject(files, options = {}) {
215
+ return unwrapApiResult(await generateProjectContext({
216
+ body: {
217
+ files: files.map(({ branchId, fileId, versionId }) => ({
218
+ branchId,
219
+ fileId,
220
+ versionId
221
+ })),
222
+ locales: options.locales?.map((locale) => resolveServiceLocale(locale)),
223
+ force: options.force
224
+ },
225
+ client: getClient(options.timeoutMs)
226
+ }));
227
+ },
228
+ loadJobStatuses,
229
+ async checkJobStatus(jobIds, timeoutMs) {
230
+ return (await loadJobStatuses(jobIds, { timeoutMs })).map(normalizeJobStatus);
231
+ },
232
+ async awaitJobs(jobIds, options) {
233
+ const result = await pollJobs(jobIds, (pendingJobIds, signal) => loadJobStatuses(pendingJobIds, { signal }), options);
234
+ return {
235
+ ...result,
236
+ jobs: result.jobs.map(normalizeJobStatus)
237
+ };
238
+ },
239
+ async enqueueFiles(files, options) {
240
+ validateFileFormatTransforms(files);
241
+ const modelProvider = options.modelProvider;
242
+ if (modelProvider !== void 0 && !isModelProvider(modelProvider)) throw new Error(createDiagnosticMessage({
243
+ source: "generaltranslation",
244
+ severity: "Error",
245
+ whatHappened: `Unsupported model provider \`${modelProvider}\``,
246
+ fix: `Use one of: ${supportedModelProviders.join(", ")}`
247
+ }));
248
+ const targetLocales = options.targetLocales.map((locale) => resolveServiceLocale(locale));
249
+ const result = await processBatches(files, async (batch) => {
250
+ const response = unwrapApiResult(await enqueueFileTranslations({
251
+ body: {
252
+ files: batch.map(({ branchId, fileId, versionId, fileName, transformFormat }) => ({
253
+ branchId,
254
+ fileId,
255
+ versionId,
256
+ fileName,
257
+ transformFormat
258
+ })),
259
+ targetLocales,
260
+ sourceLocale: options.sourceLocale ? resolveServiceLocale(options.sourceLocale) : void 0,
261
+ modelProvider,
262
+ force: options.force
263
+ },
264
+ client: getClient(options.timeout)
265
+ }));
266
+ const jobData = "jobData" in response ? response.jobData : response.data;
267
+ return Object.entries(jobData);
268
+ });
269
+ return {
270
+ jobData: Object.fromEntries(result),
271
+ locales: targetLocales,
272
+ message: `Successfully enqueued ${result.length} file translation jobs in ${Math.ceil(files.length / DEFAULT_BATCH_SIZE)} batch(es)`
273
+ };
274
+ },
275
+ async createTag(body) {
276
+ return unwrapApiResult(await createTag({
277
+ body,
278
+ client: getClient()
279
+ }));
280
+ },
281
+ async publishFiles(files) {
282
+ return unwrapApiResult(await publishFiles({
283
+ body: { files: files.map(({ fileId, versionId, branchId, publish }) => ({
284
+ fileId,
285
+ versionId,
286
+ branchId,
287
+ publish
288
+ })) },
289
+ client: getClient()
290
+ }));
291
+ },
292
+ async submitUserEditDiffs(body, options = {}) {
293
+ return processBatches(body.diffs, async (diffs) => [unwrapApiResult(await submitUserEditDiffs({
294
+ body: {
295
+ projectId: body.projectId,
296
+ diffs: diffs.map(({ diff, branchId, versionId, fileId, localContent, locale }) => ({
297
+ diff,
298
+ branchId,
299
+ versionId,
300
+ fileId,
301
+ localContent,
302
+ locale: resolveServiceLocale(locale)
303
+ }))
304
+ },
305
+ client: getClient(options.timeout)
306
+ }))]);
307
+ },
308
+ async createProject(orgId, body) {
309
+ return unwrapApiResult(await createProject({
310
+ path: { orgId },
311
+ body: {
312
+ ...body,
313
+ defaultLocale: resolveServiceLocale(body.defaultLocale)
314
+ },
315
+ client: getClient()
316
+ }));
317
+ },
318
+ /** Every project the configured credentials can read. */
319
+ async listProjects() {
320
+ return collectPages(async (cursor) => {
321
+ const { projects, nextCursor } = unwrapApiResult(await listProjects({
322
+ query: cursor ? { cursor } : void 0,
323
+ client: getClient()
324
+ }));
325
+ return {
326
+ items: projects,
327
+ nextCursor
328
+ };
329
+ });
330
+ },
331
+ /** Organizations where the signed-in user can create projects; user tokens only. */
332
+ async listOrgs() {
333
+ return collectPages(async (cursor) => {
334
+ const { orgs, nextCursor } = unwrapApiResult(await listOrgs({
335
+ query: cursor ? { cursor } : void 0,
336
+ client: getClient()
337
+ }));
338
+ return {
339
+ items: orgs,
340
+ nextCursor
341
+ };
342
+ });
343
+ },
344
+ async createProjectApiKey(projectId, body) {
345
+ return unwrapApiResult(await createProjectApiKey({
346
+ path: { projectId },
347
+ body,
348
+ client: getClient()
349
+ }));
350
+ },
351
+ loadProjectInfo,
352
+ async getProjectInfo(projectId, timeoutMs) {
353
+ const result = await loadProjectInfo(projectId, timeoutMs);
354
+ return {
355
+ ...result,
356
+ defaultLocale: resolveAliasLocale(result.defaultLocale, config?.customMapping),
357
+ currentLocales: result.currentLocales.map((locale) => resolveAliasLocale(locale, config?.customMapping))
358
+ };
359
+ },
360
+ async queryFileData(body, timeoutMs) {
361
+ const result = unwrapApiResult(await getFileInfo({
362
+ body: {
363
+ ...body,
364
+ translatedFiles: body.translatedFiles?.map((file) => ({
365
+ ...file,
366
+ locale: resolveServiceLocale(file.locale)
367
+ }))
368
+ },
369
+ client: getClient(timeoutMs)
370
+ }));
371
+ return {
372
+ ...result,
373
+ translatedFiles: result.translatedFiles.map((file) => ({
374
+ ...file,
375
+ locale: resolveAliasLocale(file.locale, config?.customMapping)
376
+ })),
377
+ sourceFiles: result.sourceFiles.map((file) => ({
378
+ ...file,
379
+ sourceLocale: resolveAliasLocale(file.sourceLocale, config?.customMapping),
380
+ locales: file.locales.map((locale) => resolveAliasLocale(locale, config?.customMapping))
381
+ }))
382
+ };
383
+ },
384
+ async querySourceFile(path, query = {}, timeoutMs) {
385
+ const result = unwrapApiResult(await getTranslationStatus({
386
+ path,
387
+ query,
388
+ client: getClient(timeoutMs)
389
+ }));
390
+ return {
391
+ ...result,
392
+ translations: result.translations.map((translation) => ({
393
+ ...translation,
394
+ locale: resolveAliasLocale(translation.locale, config?.customMapping)
395
+ })),
396
+ sourceFile: {
397
+ ...result.sourceFile,
398
+ sourceLocale: resolveAliasLocale(result.sourceFile.sourceLocale, config?.customMapping),
399
+ locales: result.sourceFile.locales.map((locale) => resolveAliasLocale(locale, config?.customMapping))
400
+ }
401
+ };
402
+ },
403
+ async downloadFileBatch(files, options = {}) {
404
+ const request = async (batch) => unwrapApiResult(await downloadFiles({
405
+ body: batch.map((file) => ({
406
+ ...file,
407
+ locale: file.locale ? resolveServiceLocale(file.locale) : void 0
408
+ })),
409
+ client: getClient(options.timeout)
410
+ }));
411
+ const responses = await processBatches(files, async (batch) => [await request(batch)]);
412
+ return {
413
+ files: responses.flatMap((response) => response.files.map((file) => ({
414
+ ...file,
415
+ ...file.locale && { locale: resolveAliasLocale(file.locale, config?.customMapping) },
416
+ data: decodeFileContent(file.data, file.fileFormat),
417
+ metadata: file.metadata
418
+ }))),
419
+ count: responses.reduce((count, response) => count + response.count, 0),
420
+ pending: responses.flatMap((response) => (response.pending ?? []).map((file) => ({
421
+ ...file,
422
+ locale: resolveAliasLocale(file.locale, config?.customMapping)
423
+ })))
424
+ };
425
+ },
426
+ async uploadSourceFiles(files, options) {
427
+ const sourceLocale = resolveServiceLocale(options.sourceLocale);
428
+ return { uploadedFiles: await processBatches(files, async (batch) => {
429
+ return unwrapApiResult(await uploadSourceFiles({
430
+ body: {
431
+ data: batch.map(({ source }) => ({ source: {
432
+ ...source,
433
+ content: encodeFileContent(source.content, source.fileFormat),
434
+ locale: resolveServiceLocale(source.locale)
435
+ } })),
436
+ sourceLocale
437
+ },
438
+ client: getClient(options.timeout)
439
+ })).uploadedFiles.map(aliasUploadedFileLocale);
440
+ }) };
441
+ },
442
+ async uploadFonts(fonts, options = {}) {
443
+ const assets = await processBatches(fonts, async (batch) => {
444
+ return unwrapApiResult(await uploadAssets({
445
+ body: { assets: batch },
446
+ client: getClient(options.timeout)
447
+ })).assets;
448
+ }, { batchSize: 50 });
449
+ return {
450
+ assets,
451
+ count: assets.length
452
+ };
453
+ },
454
+ async uploadTranslations(files, options) {
455
+ validateFileFormatTransforms(files.map(({ source }) => source));
456
+ return { uploadedFiles: await processBatches(files, async (batch) => {
457
+ return unwrapApiResult(await uploadTranslations({
458
+ body: {
459
+ data: batch.map(({ source, translations }) => ({
460
+ source: {
461
+ ...source,
462
+ content: encodeFileContent(source.content, source.fileFormat),
463
+ locale: resolveServiceLocale(source.locale)
464
+ },
465
+ translations: translations.map((translation) => ({
466
+ ...translation,
467
+ locale: resolveServiceLocale(translation.locale),
468
+ content: encodeFileContent(translation.content, translation.fileFormat)
469
+ }))
470
+ })),
471
+ sourceLocale: resolveServiceLocale(options.sourceLocale)
472
+ },
473
+ client: getClient(options.timeout)
474
+ })).uploadedFiles.map(aliasUploadedFileLocale);
475
+ }) };
476
+ }
477
+ };
478
+ }
479
+ //#endregion
480
+ //#region src/derive/utils/traverseIcu.ts
481
+ /**
482
+ * Given an ICU string, traverse the AST and call the visitor function for each element that matches the type T
483
+ * @param icu - The ICU string to traverse
484
+ * @param shouldVisit - A function that returns true if the element should be visited
485
+ * @param visitor - A function that is called for each element that matches the type T
486
+ * @returns The modified AST of the ICU string.
487
+ *
488
+ * @note This function is a heavy operation, use sparingly
489
+ */
490
+ function traverseIcu({ icuString, shouldVisit, visitor, options: { recurseIntoVisited = true, ...otherOptions } }) {
491
+ const ast = parse(icuString, otherOptions);
492
+ handleChildren(ast);
493
+ return ast;
494
+ function handleChildren(children) {
495
+ children.map(handleChild);
496
+ }
497
+ function handleChild(child) {
498
+ let visited = false;
499
+ if (shouldVisit(child)) {
500
+ visitor(child);
501
+ visited = true;
502
+ }
503
+ if (!visited || recurseIntoVisited) {
504
+ if (child.type === TYPE.select || child.type === TYPE.plural) Object.values(child.options).map((option) => option.value).map(handleChildren);
505
+ else if (child.type === TYPE.tag) handleChildren(child.children);
506
+ }
507
+ }
508
+ }
509
+ //#endregion
510
+ //#region src/derive/utils/constants.ts
511
+ const VAR_IDENTIFIER = "_gt_";
512
+ const VAR_NAME_IDENTIFIER = "_gt_var_name";
513
+ //#endregion
514
+ //#region src/derive/utils/regex.ts
515
+ const GT_INDEXED_IDENTIFIER_REGEX = new RegExp(`^${VAR_IDENTIFIER}\\d+$`);
516
+ const GT_UNINDEXED_IDENTIFIER_REGEX = new RegExp(`^${VAR_IDENTIFIER}$`);
517
+ //#endregion
518
+ //#region src/derive/utils/traverseHelpers.ts
519
+ function isGTIndexedSelectElement(child) {
520
+ return child.type === TYPE.select && GT_INDEXED_IDENTIFIER_REGEX.test(child.value) && !!child.options.other && (child.options.other.value.length === 0 || child.options.other.value.length > 0 && child.options.other.value[0]?.type === TYPE.literal);
521
+ }
522
+ function isGTUnindexedSelectElement(child) {
523
+ return child.type === TYPE.select && GT_UNINDEXED_IDENTIFIER_REGEX.test(child.value) && !!child.options.other && (child.options.other.value.length === 0 || child.options.other.value.length > 0 && child.options.other.value[0]?.type === TYPE.literal);
524
+ }
525
+ //#endregion
526
+ //#region src/derive/decodeVars.ts
527
+ /**
528
+ * Given an encoded ICU string, interpolate only _gt_ variables that have been marked with declareVar()
529
+ * @example
530
+ * const encodedIcu = "Hi" + declareVar("Brian") + ", my name is {name}"
531
+ * // 'Hi {_gt_, select, other {Brian}}, my name is {name}'
532
+ * decodeVars(encodedIcu)
533
+ * // 'Hi Brian, my name is {name}'
534
+ */
535
+ function decodeVars(icuString) {
536
+ if (!icuString.includes("_gt_")) return icuString;
537
+ const variableLocations = [];
538
+ function visitor(child) {
539
+ variableLocations.push({
540
+ start: child.location?.start.offset ?? 0,
541
+ end: child.location?.end.offset ?? 0,
542
+ value: child.options.other.value.length > 0 ? child.options.other.value[0].value : ""
543
+ });
544
+ }
545
+ traverseIcu({
546
+ icuString,
547
+ shouldVisit: isGTUnindexedSelectElement,
548
+ visitor,
549
+ options: {
550
+ recurseIntoVisited: false,
551
+ captureLocation: true
552
+ }
553
+ });
554
+ let previousIndex = 0;
555
+ const outputList = [];
556
+ for (let i = 0; i < variableLocations.length; i++) {
557
+ outputList.push(icuString.slice(previousIndex, variableLocations[i].start));
558
+ outputList.push(variableLocations[i].value);
559
+ previousIndex = variableLocations[i].end;
560
+ }
561
+ if (previousIndex < icuString.length) outputList.push(icuString.slice(previousIndex));
562
+ return outputList.join("");
563
+ }
564
+ //#endregion
565
+ //#region src/derive/utils/sanitizeVar.ts
566
+ /**
567
+ * Sanitizes string by escaping ICU syntax
568
+ *
569
+ * Sanitize arbitrary string so it does not break the following ICU message syntax:
570
+ * {_gt_, select, other {string_here}}
571
+ *
572
+ * Escapes ICU special characters by:
573
+ * 1. Doubling all single quotes (U+0027 ')
574
+ * 2. Adding a single quote before the first special character ({}<>)
575
+ * 3. Adding a single quote after the last special character ({}<>)
576
+ */
577
+ function sanitizeVar(string) {
578
+ let result = string.replace(/'/g, "''");
579
+ const specialChars = /[{}<>]/;
580
+ const firstSpecialIndex = result.search(specialChars);
581
+ if (firstSpecialIndex === -1) return result;
582
+ let lastSpecialIndex = -1;
583
+ for (let i = result.length - 1; i >= 0; i--) if (specialChars.test(result[i])) {
584
+ lastSpecialIndex = i;
585
+ break;
586
+ }
587
+ result = result.slice(0, firstSpecialIndex) + "'" + result.slice(firstSpecialIndex, lastSpecialIndex + 1) + "'" + result.slice(lastSpecialIndex + 1);
588
+ return result;
589
+ }
590
+ //#endregion
591
+ //#region src/derive/declareVar.ts
592
+ /**
593
+ * Mark as a non-translatable string. Use within a derive() call to mark content as not derivable (e.g., not possible to statically analyze).
594
+ *
595
+ * @example
596
+ * function nonDerivableFunction() {
597
+ * return Math.random();
598
+ * }
599
+ *
600
+ * function derivableFunction() {
601
+ * if (condition) {
602
+ * return declareVar(nonDerivableFunction())
603
+ * }
604
+ * return 'John Doe';
605
+ * }
606
+ *
607
+ * const gt = useGT();
608
+ * gt(`My name is ${derive(derivableFunction())}`);
609
+ *
610
+ * @param {string | number | boolean | null | undefined} variable - The variable to sanitize.
611
+ * @param {Object} [options] - The options for the sanitization.
612
+ * @param {string} [options.$name] - The name of the variable.
613
+ * @returns {string} The sanitized value.
614
+ */
615
+ function declareVar(variable, options) {
616
+ const variableSection = ` other {${sanitizeVar(String(variable ?? ""))}}`;
617
+ let nameSection = "";
618
+ if (options?.$name) nameSection = ` ${VAR_NAME_IDENTIFIER} {${sanitizeVar(options.$name)}}`;
619
+ return `{${VAR_IDENTIFIER}, select,${variableSection}${nameSection}}`;
620
+ }
621
+ //#endregion
622
+ //#region src/derive/derive.ts
623
+ /**
624
+ * Marks content as derivable by the GT compiler and CLI.
625
+ *
626
+ * Use `derive()` when a translation string or context needs content that is
627
+ * computed from source code, but should still be discovered during extraction
628
+ * instead of treated as a runtime interpolation variable. The CLI attempts to
629
+ * resolve the derivable expression into every possible static value and
630
+ * includes those values in the source content that gets translated.
631
+ *
632
+ * `derive()` returns its argument unchanged at runtime.
633
+ *
634
+ * Run `gt validate` after adding or changing `derive()` calls to verify that
635
+ * each derivable expression can be resolved by the CLI before translating or
636
+ * building.
637
+ *
638
+ * @example
639
+ * ```jsx
640
+ * function getSubject() {
641
+ * return (Math.random() > 0.5) ? "Alice" : "Brian";
642
+ * }
643
+ * ...
644
+ * gt(`My name is ${derive(getSubject())}`);
645
+ * ```
646
+ *
647
+ * @param {T extends string | boolean | number | null | undefined} content - Content to derive for translation extraction.
648
+ * @returns {T} The same content, unchanged at runtime.
649
+ */
650
+ function derive(content) {
651
+ return content;
652
+ }
653
+ //#endregion
654
+ export { isGTUnindexedSelectElement as a, createGtApiAdapter as c, decodeFileContent as d, encode as f, isGTIndexedSelectElement as i, isSupportedFileFormatTransform as l, declareVar as n, VAR_IDENTIFIER as o, encodeFileContent as p, decodeVars as r, traverseIcu as s, derive as t, decode as u };
655
+
656
+ //# sourceMappingURL=derive-Cv5_y8Tf.mjs.map