generaltranslation 9.5.9 → 9.5.11

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 (36) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/adapter/createGtApi.d.ts +21 -6
  3. package/dist/adapter/createGtApi.js +204 -17
  4. package/dist/{derive-BcAOcvDD.mjs → derive-BBD2mTMR.mjs} +115 -13
  5. package/dist/derive-BBD2mTMR.mjs.map +1 -0
  6. package/dist/{derive-Bj85yN5p.cjs → derive-DxbxGWPL.cjs} +114 -13
  7. package/dist/derive-DxbxGWPL.cjs.map +1 -0
  8. package/dist/{id-DJ_59q21.cjs → id-BdPEULmV.cjs} +46 -34
  9. package/dist/id-BdPEULmV.cjs.map +1 -0
  10. package/dist/id.cjs +1 -1
  11. package/dist/id.d.cts +1 -1
  12. package/dist/id.d.mts +1 -1
  13. package/dist/index.cjs +2 -2
  14. package/dist/index.d.cts +1 -1
  15. package/dist/index.d.mts +1 -1
  16. package/dist/index.mjs +1 -1
  17. package/dist/internal.cjs +3 -3
  18. package/dist/internal.d.cts +24 -11
  19. package/dist/internal.d.mts +24 -11
  20. package/dist/internal.mjs +1 -1
  21. package/dist/openapi.json +576 -0
  22. package/dist/runtime.cjs +1 -1
  23. package/dist/runtime.d.cts +1 -1
  24. package/dist/runtime.d.mts +1 -1
  25. package/dist/{runtimeTranslate-B8BLxD_U.cjs → runtimeTranslate-DWi4UDyh.cjs} +2 -2
  26. package/dist/{runtimeTranslate-B8BLxD_U.cjs.map → runtimeTranslate-DWi4UDyh.cjs.map} +1 -1
  27. package/dist/{types-BxgnFr8M.d.cts → types-Btkr-Fkj.d.cts} +13 -13
  28. package/dist/{types-Ix4SHG5H.d.mts → types-yVJ-ivd_.d.mts} +13 -13
  29. package/dist/types.d.cts +1 -1
  30. package/dist/types.d.mts +1 -1
  31. package/dist/utils/base64.d.ts +4 -0
  32. package/dist/utils/base64.js +14 -5
  33. package/package.json +2 -2
  34. package/dist/derive-BcAOcvDD.mjs.map +0 -1
  35. package/dist/derive-Bj85yN5p.cjs.map +0 -1
  36. package/dist/id-DJ_59q21.cjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # generaltranslation
2
2
 
3
+ ## 9.5.11
4
+
5
+ ### Patch Changes
6
+
7
+ - [#2661](https://github.com/generaltranslation/gt/pull/2661) [`b3c3647`](https://github.com/generaltranslation/gt/commit/b3c3647239a6c44c3549e722b7001b83624865f8) Thanks [@chenxin-yan](https://github.com/chenxin-yan)! - Source files over the upload route's inline limit (20MB, or more than a request can carry with their `formatMetadata`) are uploaded straight to storage, content and `formatMetadata` both, and sent by reference, so `gt stage` and `gt translate` no longer fail with 413 on large files or large source-code context. `@generaltranslation/api` adds `createFileUploads`, `putFileUpload`, and `uploadSourceFileReferences`.
8
+
9
+ - Updated dependencies [[`b3c3647`](https://github.com/generaltranslation/gt/commit/b3c3647239a6c44c3549e722b7001b83624865f8)]:
10
+ - @generaltranslation/api@0.6.0
11
+
12
+ ## 9.5.10
13
+
14
+ ### Patch Changes
15
+
16
+ - [#2653](https://github.com/generaltranslation/gt/pull/2653) [`e1c64a3`](https://github.com/generaltranslation/gt/commit/e1c64a3c27c7a05ffeb81eb2d04ace795d0c3ab5) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - `previewUrl` resolvers now get the Sanity language id of the page as a second argument, `resolve(doc, { language })`, so each locale links to its own page. Imported translations send their page as their preview URL, resolved from the document they were written to. Adds `updateFiles` to the API client and adapter for updating source files and translations.
17
+
18
+ - Updated dependencies [[`e1c64a3`](https://github.com/generaltranslation/gt/commit/e1c64a3c27c7a05ffeb81eb2d04ace795d0c3ab5)]:
19
+ - @generaltranslation/api@0.5.7
20
+
3
21
  ## 9.5.9
4
22
 
5
23
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- import { createApiClient, type ApiClientConfig, type AwaitJobsOptions, type CreateBranchData, type CreateOrgApiKeyData, type CreateProjectApiKeyData, type CreateProjectData, type CreateTagData, type DownloadFilesData, type EnqueueFileTranslationsData, type GenerateProjectContextData, type GetBranchInfoData, type GetFileInfoData, type GetTranslationJobInfoResponse, type GetTranslationStatusData, type ProcessFileMovesData, type PublishFilesData, type SubmitUserEditDiffsData, type UploadAssetsData, type UploadSourceFilesData, type UploadTranslationsData } from '@generaltranslation/api';
1
+ import { createApiClient, type ApiClientConfig, type AwaitJobsOptions, type CreateBranchData, type CreateOrgApiKeyData, type CreateProjectApiKeyData, type CreateProjectData, type CreateTagData, type DownloadFilesData, type FileFormat, type EnqueueFileTranslationsData, type GenerateProjectContextData, type GetBranchInfoData, type GetFileInfoData, type GetTranslationJobInfoResponse, type GetTranslationStatusData, type ProcessFileMovesData, type PublishFilesData, type SubmitUserEditDiffsData, type UpdateFilesData, type UploadAssetsData, type UploadSourceFilesData, type UploadTranslationsData } from '@generaltranslation/api';
2
2
  import type { CustomMapping } from '@generaltranslation/format/types';
3
3
  import type { DownloadedFile } from '../types-dir/api/downloadFileBatch';
4
4
  import type { TranslateManyEntry, TranslateOptions } from '../types-dir/api/entry';
@@ -112,6 +112,20 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
112
112
  error?: string;
113
113
  }>;
114
114
  }>;
115
+ /** Updates source files, or their translations when a file names a locale; each request of up to 100 files writes all or nothing. */
116
+ updateFiles(files: UpdateFilesData["body"]["files"], options?: {
117
+ timeout?: number;
118
+ }): Promise<{
119
+ files: {
120
+ branchId: string;
121
+ fileId: string;
122
+ versionId: string;
123
+ locale?: string;
124
+ metadata: {
125
+ previewUrl?: string | null;
126
+ };
127
+ }[];
128
+ }>;
115
129
  submitUserEditDiffs(body: SubmitUserEditDiffsData["body"], options?: {
116
130
  timeout?: number;
117
131
  }): Promise<{
@@ -178,7 +192,7 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
178
192
  branchId: string;
179
193
  fileId: string;
180
194
  versionId: string;
181
- fileFormat: import("@generaltranslation/api").FileFormat;
195
+ fileFormat: FileFormat;
182
196
  dataFormat: string | null;
183
197
  createdAt: string;
184
198
  updatedAt: string;
@@ -193,7 +207,7 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
193
207
  fileId: string;
194
208
  versionId: string;
195
209
  fileName: string;
196
- fileFormat: import("@generaltranslation/api").FileFormat;
210
+ fileFormat: FileFormat;
197
211
  dataFormat: string | null;
198
212
  createdAt: string;
199
213
  updatedAt: string;
@@ -217,7 +231,7 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
217
231
  fileId: string;
218
232
  versionId: string;
219
233
  fileName: string;
220
- fileFormat: import("@generaltranslation/api").FileFormat;
234
+ fileFormat: FileFormat;
221
235
  dataFormat: string | null;
222
236
  createdAt: string;
223
237
  updatedAt: string;
@@ -235,6 +249,7 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
235
249
  versionId: string;
236
250
  }[];
237
251
  }>;
252
+ /** Sends each file inline while it and its request fit the legacy route's limits, otherwise PUTs its bytes to storage and uploads a reference to them. */
238
253
  uploadSourceFiles(files: Array<{
239
254
  source: UploadSourceFilesData["body"]["data"][number]["source"];
240
255
  }>, options: {
@@ -246,7 +261,7 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
246
261
  fileId: string;
247
262
  versionId: string;
248
263
  fileName: string;
249
- fileFormat: import("@generaltranslation/api").FileFormat;
264
+ fileFormat: FileFormat;
250
265
  dataFormat?: import("@generaltranslation/api").DataFormat;
251
266
  locale?: string;
252
267
  }[];
@@ -270,7 +285,7 @@ export declare function createGtApiAdapter(defaultConfig?: GtApiAdapterConfig):
270
285
  fileId: string;
271
286
  versionId: string;
272
287
  fileName: string;
273
- fileFormat: import("@generaltranslation/api").FileFormat;
288
+ fileFormat: FileFormat;
274
289
  dataFormat?: import("@generaltranslation/api").DataFormat;
275
290
  locale?: string;
276
291
  }[];
@@ -45,6 +45,17 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
45
45
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
46
46
  }
47
47
  };
48
+ var __rest = (this && this.__rest) || function (s, e) {
49
+ var t = {};
50
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
51
+ t[p] = s[p];
52
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
53
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
54
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
55
+ t[p[i]] = s[p[i]];
56
+ }
57
+ return t;
58
+ };
48
59
  var __asyncValues = (this && this.__asyncValues) || function (o) {
49
60
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
50
61
  var m = o[Symbol.asyncIterator], i;
@@ -61,14 +72,100 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
61
72
  }
62
73
  return to.concat(ar || Array.prototype.slice.call(from));
63
74
  };
64
- import { createApiClient, createBranch, createOrgApiKey, createProject, createProjectApiKey, createTag, DEFAULT_BATCH_SIZE, downloadFiles, enqueueFileTranslations, generateProjectContext, getBranchInfo, getFileInfo, getOrphanedFiles, getProjectInfo, getTranslationJobInfo, getTranslationStatus, listOrgs, listProjects, paginate, pollJobs, processBatches, processFileMoves, publishFiles, submitUserEditDiffs, uploadAssets, uploadSourceFiles, uploadTranslations, } from '@generaltranslation/api';
75
+ import { createApiClient, createBranch, createFileUploads, createOrgApiKey, createProject, createProjectApiKey, createTag, DEFAULT_BATCH_SIZE, downloadFiles, enqueueFileTranslations, generateProjectContext, getBranchInfo, getFileInfo, getOrphanedFiles, getProjectInfo, getTranslationJobInfo, getTranslationStatus, listOrgs, listProjects, paginate, pollJobs, processBatches, processFileMoves, publishFiles, putFileUpload, submitUserEditDiffs, updateFiles, uploadAssets, uploadSourceFileReferences, uploadSourceFiles, uploadTranslations, } from '@generaltranslation/api';
76
+ import { sha256 } from '@noble/hashes/sha2.js';
77
+ import { bytesToHex } from '@noble/hashes/utils.js';
65
78
  import { resolveAliasLocale, resolveCanonicalLocale, standardizeLocale, } from '@generaltranslation/format';
66
79
  import { createDiagnosticMessage } from '../logging/diagnostics';
67
80
  import { translate as translateWithConfig, translateMany as translateManyWithConfig, } from '../translate/runtimeTranslate';
68
- import { decodeFileContent, encodeFileContent } from '../utils/base64';
81
+ import { decodeBytes, decodedByteLength, decodeFileContent, encodeFileContent, } from '../utils/base64';
69
82
  import { unwrapApiResult } from '../translate/utils/unwrapApiResult';
70
83
  import { validateFileFormatTransforms } from '../translate/utils/validateFileFormatTransform';
71
84
  import { isModelProvider, supportedModelProviders } from './modelProvider';
85
+ // Which files stay on the legacy upload route; the rest go by reference. The
86
+ // route's frozen contract rejects inline content over 20MB per file, and
87
+ // Cloudflare rejects request bodies over 100MB.
88
+ var MAX_LEGACY_INLINE_FILE_BYTES = 20000000;
89
+ var MAX_INLINE_REQUEST_BYTES = 90 * 1024 * 1024;
90
+ function jsonByteLength(value) {
91
+ return value === undefined
92
+ ? 0
93
+ : new TextEncoder().encode(JSON.stringify(value)).byteLength;
94
+ }
95
+ /** PUTs a source file's bytes, and its formatMetadata when it has any, to storage unless the project already has them, then uploads it by reference to both. */
96
+ function uploadSourceFileReference(_a, options) {
97
+ return __awaiter(this, void 0, void 0, function () {
98
+ var client, projectId, sourceLocale, storageTransport, stage, file, metadata, staged, created, _b, result, _c, _status, _error, _code, uploaded;
99
+ var content = _a.content, formatMetadata = _a.formatMetadata, source = __rest(_a, ["content", "formatMetadata"]);
100
+ return __generator(this, function (_d) {
101
+ switch (_d.label) {
102
+ case 0:
103
+ client = options.client, projectId = options.projectId, sourceLocale = options.sourceLocale, storageTransport = options.storageTransport;
104
+ stage = function (bytes, fileFormat) { return ({
105
+ bytes: bytes,
106
+ fileFormat: fileFormat,
107
+ sha256: bytesToHex(sha256(bytes)),
108
+ }); };
109
+ file = stage(decodeBytes(content), source.fileFormat);
110
+ metadata = formatMetadata &&
111
+ stage(new TextEncoder().encode(JSON.stringify(formatMetadata)), 'JSON');
112
+ staged = metadata ? [file, metadata] : [file];
113
+ _b = unwrapApiResult;
114
+ return [4 /*yield*/, createFileUploads({
115
+ client: client,
116
+ path: { projectId: projectId },
117
+ body: {
118
+ files: staged.map(function (_a) {
119
+ var hash = _a.sha256, fileFormat = _a.fileFormat, bytes = _a.bytes;
120
+ return ({
121
+ sha256: hash,
122
+ fileFormat: fileFormat,
123
+ size: bytes.byteLength,
124
+ });
125
+ }),
126
+ },
127
+ })];
128
+ case 1:
129
+ created = _b.apply(void 0, [_d.sent()]).files;
130
+ return [4 /*yield*/, Promise.all(created.map(function (_a) {
131
+ var _b;
132
+ var hash = _a.sha256, upload = _a.upload;
133
+ var bytes = (_b = staged.find(function (item) { return item.sha256 === hash; })) === null || _b === void 0 ? void 0 : _b.bytes;
134
+ return upload && bytes && putFileUpload(upload, bytes, storageTransport);
135
+ }))];
136
+ case 2:
137
+ _d.sent();
138
+ _c = unwrapApiResult;
139
+ return [4 /*yield*/, uploadSourceFileReferences({
140
+ client: client,
141
+ path: { projectId: projectId },
142
+ body: {
143
+ data: [
144
+ {
145
+ source: __assign(__assign(__assign({}, source), { upload: { sha256: file.sha256 } }), (metadata && {
146
+ formatMetadata: { upload: { sha256: metadata.sha256 } },
147
+ })),
148
+ },
149
+ ],
150
+ sourceLocale: sourceLocale,
151
+ },
152
+ })];
153
+ case 3:
154
+ result = _c.apply(void 0, [_d.sent()]).results[0];
155
+ if ((result === null || result === void 0 ? void 0 : result.status) !== 'succeeded') {
156
+ throw new Error(createDiagnosticMessage({
157
+ source: 'generaltranslation',
158
+ severity: 'Error',
159
+ whatHappened: "Source file `".concat(source.fileName, "` could not be uploaded"),
160
+ details: result === null || result === void 0 ? void 0 : result.error,
161
+ }));
162
+ }
163
+ _status = result.status, _error = result.error, _code = result.code, uploaded = __rest(result, ["status", "error", "code"]);
164
+ return [2 /*return*/, uploaded];
165
+ }
166
+ });
167
+ });
168
+ }
72
169
  function collect(iterable) {
73
170
  return __awaiter(this, void 0, void 0, function () {
74
171
  var items, item, e_1_1;
@@ -501,6 +598,49 @@ export function createGtApiAdapter(defaultConfig) {
501
598
  });
502
599
  });
503
600
  },
601
+ /** Updates source files, or their translations when a file names a locale; each request of up to 100 files writes all or nothing. */
602
+ updateFiles: function (files_1) {
603
+ return __awaiter(this, arguments, void 0, function (files, options) {
604
+ var projectId, updated;
605
+ var _this = this;
606
+ if (options === void 0) { options = {}; }
607
+ return __generator(this, function (_a) {
608
+ switch (_a.label) {
609
+ case 0:
610
+ projectId = getConfig().projectId;
611
+ if (!projectId) {
612
+ throw new Error('Project ID is required to update files');
613
+ }
614
+ return [4 /*yield*/, processBatches(files, function (batch) { return __awaiter(_this, void 0, void 0, function () {
615
+ var response, _a;
616
+ return __generator(this, function (_b) {
617
+ switch (_b.label) {
618
+ case 0:
619
+ _a = unwrapApiResult;
620
+ return [4 /*yield*/, updateFiles({
621
+ body: {
622
+ files: batch.map(function (file) {
623
+ return file.locale === undefined
624
+ ? file
625
+ : __assign(__assign({}, file), { locale: resolveServiceLocale(file.locale) });
626
+ }),
627
+ },
628
+ path: { projectId: projectId },
629
+ client: getClient(options.timeout),
630
+ })];
631
+ case 1:
632
+ response = _a.apply(void 0, [_b.sent()]);
633
+ return [2 /*return*/, response.files.map(aliasUploadedFileLocale)];
634
+ }
635
+ });
636
+ }); })];
637
+ case 1:
638
+ updated = _a.sent();
639
+ return [2 /*return*/, { files: updated }];
640
+ }
641
+ });
642
+ });
643
+ },
504
644
  submitUserEditDiffs: function (body_1) {
505
645
  return __awaiter(this, arguments, void 0, function (body, options) {
506
646
  var _this = this;
@@ -716,40 +856,87 @@ export function createGtApiAdapter(defaultConfig) {
716
856
  });
717
857
  });
718
858
  },
859
+ /** Sends each file inline while it and its request fit the legacy route's limits, otherwise PUTs its bytes to storage and uploads a reference to them. */
719
860
  uploadSourceFiles: function (files, options) {
720
861
  return __awaiter(this, void 0, void 0, function () {
721
- var sourceLocale, result;
862
+ var sourceLocale, _a, projectId, fetch, retryPolicy, result;
722
863
  var _this = this;
723
- return __generator(this, function (_a) {
724
- switch (_a.label) {
864
+ return __generator(this, function (_b) {
865
+ switch (_b.label) {
725
866
  case 0:
726
867
  sourceLocale = resolveServiceLocale(options.sourceLocale);
868
+ _a = getConfig(), projectId = _a.projectId, fetch = _a.fetch, retryPolicy = _a.retryPolicy;
727
869
  return [4 /*yield*/, processBatches(files, function (batch) { return __awaiter(_this, void 0, void 0, function () {
728
- var response, _a;
729
- return __generator(this, function (_b) {
730
- switch (_b.label) {
870
+ var client, inlineBytes, sources, inlineSources, uploaded, _a, _b, _i, sources_1, _c, inline, source, _d, _e;
871
+ return __generator(this, function (_f) {
872
+ switch (_f.label) {
731
873
  case 0:
732
- _a = unwrapApiResult;
874
+ client = getClient(options.timeout);
875
+ inlineBytes = 0;
876
+ sources = batch.map(function (_a) {
877
+ var source = _a.source;
878
+ var content = encodeFileContent(source.content, source.fileFormat);
879
+ var size = content.length + jsonByteLength(source.formatMetadata);
880
+ var inline = !projectId ||
881
+ (decodedByteLength(content) <= MAX_LEGACY_INLINE_FILE_BYTES &&
882
+ inlineBytes + size <= MAX_INLINE_REQUEST_BYTES);
883
+ if (inline)
884
+ inlineBytes += size;
885
+ return {
886
+ inline: inline,
887
+ source: __assign(__assign({}, source), { content: content, locale: resolveServiceLocale(source.locale) }),
888
+ };
889
+ });
890
+ inlineSources = sources.filter(function (_a) {
891
+ var inline = _a.inline;
892
+ return inline;
893
+ });
894
+ if (!(inlineSources.length > 0)) return [3 /*break*/, 2];
895
+ _b = unwrapApiResult;
733
896
  return [4 /*yield*/, uploadSourceFiles({
734
897
  body: {
735
- data: batch.map(function (_a) {
898
+ data: inlineSources.map(function (_a) {
736
899
  var source = _a.source;
737
- return ({
738
- source: __assign(__assign({}, source), { content: encodeFileContent(source.content, source.fileFormat), locale: resolveServiceLocale(source.locale) }),
739
- });
900
+ return ({ source: source });
740
901
  }),
741
902
  sourceLocale: sourceLocale,
742
903
  },
743
- client: getClient(options.timeout),
904
+ client: client,
744
905
  })];
745
906
  case 1:
746
- response = _a.apply(void 0, [_b.sent()]);
747
- return [2 /*return*/, response.uploadedFiles.map(aliasUploadedFileLocale)];
907
+ _a = _b.apply(void 0, [_f.sent()]).uploadedFiles;
908
+ return [3 /*break*/, 3];
909
+ case 2:
910
+ _a = [];
911
+ _f.label = 3;
912
+ case 3:
913
+ uploaded = _a;
914
+ _i = 0, sources_1 = sources;
915
+ _f.label = 4;
916
+ case 4:
917
+ if (!(_i < sources_1.length)) return [3 /*break*/, 7];
918
+ _c = sources_1[_i], inline = _c.inline, source = _c.source;
919
+ if (inline)
920
+ return [3 /*break*/, 6];
921
+ _e = (_d = uploaded).push;
922
+ return [4 /*yield*/, uploadSourceFileReference(source, {
923
+ client: client,
924
+ projectId: projectId,
925
+ sourceLocale: sourceLocale,
926
+ storageTransport: { fetch: fetch, retryPolicy: retryPolicy },
927
+ })];
928
+ case 5:
929
+ _e.apply(_d, [_f.sent()]);
930
+ _f.label = 6;
931
+ case 6:
932
+ _i++;
933
+ return [3 /*break*/, 4];
934
+ case 7: return [2 /*return*/, uploaded.map(aliasUploadedFileLocale)];
748
935
  }
749
936
  });
750
937
  }); })];
751
938
  case 1:
752
- result = _a.sent();
939
+ result = _b.sent();
753
940
  return [2 /*return*/, { uploadedFiles: result }];
754
941
  }
755
942
  });
@@ -1,7 +1,9 @@
1
1
  import { a as unwrapApiResult, n as translateMany, o as isModelProvider, s as supportedModelProviders, t as translate$1 } from "./runtimeTranslate-CRWJMYly.mjs";
2
2
  import { t as createDiagnosticMessage } from "./diagnostics-DKA2SkZB.mjs";
3
3
  import { n as isBinaryFileFormat } from "./file-BZmC4OTj.mjs";
4
- import { DEFAULT_BATCH_SIZE, createApiClient, createBranch, createOrgApiKey, createProject, createProjectApiKey, createTag, downloadFiles, enqueueFileTranslations, generateProjectContext, getBranchInfo, getFileInfo, getOrphanedFiles, getProjectInfo, getTranslationJobInfo, getTranslationStatus, listOrgs, listProjects, paginate, pollJobs, processBatches, processFileMoves, publishFiles, submitUserEditDiffs, uploadAssets, uploadSourceFiles, uploadTranslations } from "@generaltranslation/api";
4
+ import { DEFAULT_BATCH_SIZE, createApiClient, createBranch, createFileUploads, createOrgApiKey, createProject, createProjectApiKey, createTag, downloadFiles, enqueueFileTranslations, generateProjectContext, getBranchInfo, getFileInfo, getOrphanedFiles, getProjectInfo, getTranslationJobInfo, getTranslationStatus, listOrgs, listProjects, paginate, pollJobs, processBatches, processFileMoves, publishFiles, putFileUpload, submitUserEditDiffs, updateFiles, uploadAssets, uploadSourceFileReferences, uploadSourceFiles, uploadTranslations } from "@generaltranslation/api";
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { bytesToHex } from "@noble/hashes/utils.js";
5
7
  import { resolveAliasLocale, resolveCanonicalLocale, standardizeLocale } from "@generaltranslation/format";
6
8
  import { TYPE, parse } from "@generaltranslation/icu";
7
9
  //#region src/utils/base64.ts
@@ -14,10 +16,17 @@ function encode(data) {
14
16
  }
15
17
  function decode(base64) {
16
18
  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);
19
+ return new TextDecoder().decode(decodeBytes(base64));
20
+ }
21
+ /** The bytes a base64 string encodes. */
22
+ function decodeBytes(base64) {
23
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(base64, "base64"));
24
+ return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
25
+ }
26
+ /** The number of bytes a padded base64 string encodes. */
27
+ function decodedByteLength(base64) {
28
+ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
29
+ return base64.length / 4 * 3 - padding;
21
30
  }
22
31
  function encodeFileContent(content, fileFormat) {
23
32
  return isBinaryFileFormat(fileFormat) ? content : encode(content);
@@ -81,6 +90,56 @@ function validateFileFormatTransforms(files) {
81
90
  }
82
91
  //#endregion
83
92
  //#region src/adapter/createGtApi.ts
93
+ const MAX_LEGACY_INLINE_FILE_BYTES = 2e7;
94
+ const MAX_INLINE_REQUEST_BYTES = 90 * 1024 * 1024;
95
+ function jsonByteLength(value) {
96
+ return value === void 0 ? 0 : new TextEncoder().encode(JSON.stringify(value)).byteLength;
97
+ }
98
+ /** PUTs a source file's bytes, and its formatMetadata when it has any, to storage unless the project already has them, then uploads it by reference to both. */
99
+ async function uploadSourceFileReference({ content, formatMetadata, ...source }, options) {
100
+ const { client, projectId, sourceLocale, storageTransport } = options;
101
+ const stage = (bytes, fileFormat) => ({
102
+ bytes,
103
+ fileFormat,
104
+ sha256: bytesToHex(sha256(bytes))
105
+ });
106
+ const file = stage(decodeBytes(content), source.fileFormat);
107
+ const metadata = formatMetadata && stage(new TextEncoder().encode(JSON.stringify(formatMetadata)), "JSON");
108
+ const staged = metadata ? [file, metadata] : [file];
109
+ const { files: created } = unwrapApiResult(await createFileUploads({
110
+ client,
111
+ path: { projectId },
112
+ body: { files: staged.map(({ sha256: hash, fileFormat, bytes }) => ({
113
+ sha256: hash,
114
+ fileFormat,
115
+ size: bytes.byteLength
116
+ })) }
117
+ }));
118
+ await Promise.all(created.map(({ sha256: hash, upload }) => {
119
+ const bytes = staged.find((item) => item.sha256 === hash)?.bytes;
120
+ return upload && bytes && putFileUpload(upload, bytes, storageTransport);
121
+ }));
122
+ const { results: [result] } = unwrapApiResult(await uploadSourceFileReferences({
123
+ client,
124
+ path: { projectId },
125
+ body: {
126
+ data: [{ source: {
127
+ ...source,
128
+ upload: { sha256: file.sha256 },
129
+ ...metadata && { formatMetadata: { upload: { sha256: metadata.sha256 } } }
130
+ } }],
131
+ sourceLocale
132
+ }
133
+ }));
134
+ if (result?.status !== "succeeded") throw new Error(createDiagnosticMessage({
135
+ source: "generaltranslation",
136
+ severity: "Error",
137
+ whatHappened: `Source file \`${source.fileName}\` could not be uploaded`,
138
+ details: result?.error
139
+ }));
140
+ const { status: _status, error: _error, code: _code, ...uploaded } = result;
141
+ return uploaded;
142
+ }
84
143
  async function collect(iterable) {
85
144
  const items = [];
86
145
  for await (const item of iterable) items.push(item);
@@ -286,6 +345,21 @@ function createGtApiAdapter(defaultConfig) {
286
345
  client: getClient()
287
346
  }));
288
347
  },
348
+ /** Updates source files, or their translations when a file names a locale; each request of up to 100 files writes all or nothing. */
349
+ async updateFiles(files, options = {}) {
350
+ const { projectId } = getConfig();
351
+ if (!projectId) throw new Error("Project ID is required to update files");
352
+ return { files: await processBatches(files, async (batch) => {
353
+ return unwrapApiResult(await updateFiles({
354
+ body: { files: batch.map((file) => file.locale === void 0 ? file : {
355
+ ...file,
356
+ locale: resolveServiceLocale(file.locale)
357
+ }) },
358
+ path: { projectId },
359
+ client: getClient(options.timeout)
360
+ })).files.map(aliasUploadedFileLocale);
361
+ }) };
362
+ },
289
363
  async submitUserEditDiffs(body, options = {}) {
290
364
  return processBatches(body.diffs, async (diffs) => [unwrapApiResult(await submitUserEditDiffs({
291
365
  body: {
@@ -409,20 +483,48 @@ function createGtApiAdapter(defaultConfig) {
409
483
  })))
410
484
  };
411
485
  },
486
+ /** Sends each file inline while it and its request fit the legacy route's limits, otherwise PUTs its bytes to storage and uploads a reference to them. */
412
487
  async uploadSourceFiles(files, options) {
413
488
  const sourceLocale = resolveServiceLocale(options.sourceLocale);
489
+ const { projectId, fetch, retryPolicy } = getConfig();
414
490
  return { uploadedFiles: await processBatches(files, async (batch) => {
415
- return unwrapApiResult(await uploadSourceFiles({
416
- body: {
417
- data: batch.map(({ source }) => ({ source: {
491
+ const client = getClient(options.timeout);
492
+ let inlineBytes = 0;
493
+ const sources = batch.map(({ source }) => {
494
+ const content = encodeFileContent(source.content, source.fileFormat);
495
+ const size = content.length + jsonByteLength(source.formatMetadata);
496
+ const inline = !projectId || decodedByteLength(content) <= MAX_LEGACY_INLINE_FILE_BYTES && inlineBytes + size <= MAX_INLINE_REQUEST_BYTES;
497
+ if (inline) inlineBytes += size;
498
+ return {
499
+ inline,
500
+ source: {
418
501
  ...source,
419
- content: encodeFileContent(source.content, source.fileFormat),
502
+ content,
420
503
  locale: resolveServiceLocale(source.locale)
421
- } })),
504
+ }
505
+ };
506
+ });
507
+ const inlineSources = sources.filter(({ inline }) => inline);
508
+ const uploaded = inlineSources.length > 0 ? unwrapApiResult(await uploadSourceFiles({
509
+ body: {
510
+ data: inlineSources.map(({ source }) => ({ source })),
422
511
  sourceLocale
423
512
  },
424
- client: getClient(options.timeout)
425
- })).uploadedFiles.map(aliasUploadedFileLocale);
513
+ client
514
+ })).uploadedFiles : [];
515
+ for (const { inline, source } of sources) {
516
+ if (inline) continue;
517
+ uploaded.push(await uploadSourceFileReference(source, {
518
+ client,
519
+ projectId,
520
+ sourceLocale,
521
+ storageTransport: {
522
+ fetch,
523
+ retryPolicy
524
+ }
525
+ }));
526
+ }
527
+ return uploaded.map(aliasUploadedFileLocale);
426
528
  }) };
427
529
  },
428
530
  async uploadFonts(fonts, options = {}) {
@@ -639,4 +741,4 @@ function derive(content) {
639
741
  //#endregion
640
742
  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 };
641
743
 
642
- //# sourceMappingURL=derive-BcAOcvDD.mjs.map
744
+ //# sourceMappingURL=derive-BBD2mTMR.mjs.map