Repository navigation
Expand file tree
/
Copy pathdeeplClient.ts
More file actions
1315 lines (1211 loc) · 53.3 KB
/
Copy pathdeeplClient.ts
File metadata and controls
1315 lines (1211 loc) · 53.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
import { Translator, checkStatusCode } from './translator';
import {
DeepLClientOptions,
WriteResult,
MultilingualGlossaryDictionaryEntries,
MultilingualGlossaryInfo,
MultilingualGlossaryDictionaryInfo,
MultilingualGlossaryDictionaryApiResponse,
MultilingualGlossaryDictionaryEntriesApiResponse,
GlossaryId,
ListMultilingualGlossaryApiResponse,
StyleRuleInfo,
StyleRuleInfoApiResponse,
StyleId,
CustomInstruction,
TranslationMemoryId,
TranslationMemoryInfo,
TranslationMemoryExport,
TranslationMemoryImport,
TranslationMemoryJob,
TranslationMemorySegments,
TranslationMemorySegmentsOptions,
TranslationMemoryJobStatus,
} from './types';
import {
parseMultilingualGlossaryDictionaryInfo,
parseMultilingualGlossaryInfo,
parseWriteResultArray,
parseMultilingualGlossaryDictionaryEntries,
parseListMultilingualGlossaries,
parseStyleRuleInfoList,
parseStyleRuleInfo,
parseCustomInstruction,
parseTranslationMemoryExport,
parseTranslationMemoryImport,
parseTranslationMemoryInfoJson,
parseTranslationMemoryInfoList,
parseTranslationMemoryJob,
parseTranslationMemorySegments,
} from './parsing';
import {
appendCsvDictionaryEntries,
appendDictionaryEntries,
appendTextsAndReturnIsSingular,
extractGlossaryId,
extractTranslationMemoryId,
logInfo,
timeout,
} from './utils';
import { ArgumentError, DeepLError, GlossaryNotFoundError } from './errors';
import { IncomingMessage } from 'http';
import * as fs from 'fs';
import * as path from 'path';
export type CustomInstructionRequestBody = {
label: string;
prompt: string;
source_language?: string;
};
export type CreateStyleRuleRequestBody = {
name: string;
language: string;
configured_rules?: Record<string, Record<string, string>>;
custom_instructions?: CustomInstructionRequestBody[];
};
export enum WritingStyle {
ACADEMIC = 'academic',
BUSINESS = 'business',
CASUAL = 'casual',
DEFAULT = 'default',
PREFER_ACADEMIC = 'prefer_academic',
PREFER_BUSINESS = 'prefer_business',
PREFER_CASUAL = 'prefer_casual',
PREFER_SIMPLE = 'prefer_simple',
SIMPLE = 'simple',
}
export enum WritingTone {
CONFIDENT = 'confident',
DEFAULT = 'default',
DIPLOMATIC = 'diplomatic',
ENTHUSIASTIC = 'enthusiastic',
FRIENDLY = 'friendly',
PREFER_CONFIDENT = 'prefer_confident',
PREFER_DIPLOMATIC = 'prefer_diplomatic',
PREFER_ENTHUSIASTIC = 'prefer_enthusiastic',
PREFER_FRIENDLY = 'prefer_friendly',
}
export class DeepLClient extends Translator {
constructor(authKey: string, options: DeepLClientOptions = {}) {
super(authKey, options);
}
async rephraseText<T extends string | string[]>(
texts: T,
targetLang?: string | null,
writingStyle?: string | null,
tone?: string | null,
): Promise<T extends string ? WriteResult : WriteResult[]> {
const data = new URLSearchParams();
if (targetLang) {
data.append('target_lang', targetLang);
}
if (writingStyle) {
data.append('writing_style', writingStyle);
}
if (tone) {
data.append('tone', tone);
}
const singular = appendTextsAndReturnIsSingular(data, texts);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'POST',
'/v2/write/rephrase',
{ data },
);
await checkStatusCode(statusCode, content);
const writeResults = parseWriteResultArray(content);
return (singular ? writeResults[0] : writeResults) as T extends string
? WriteResult
: WriteResult[];
}
/**
* Creates a glossary with given name with all of the specified
* dictionaries, each with their own language pair and entries. The
* glossary may be used in the translateText functions.
*
* Only certain language pairs are supported. The available language pairs
* can be queried using getGlossaryLanguages(). Glossaries are not
* regional specific: a glossary with target language EN may be used to
* translate texts into both EN-US and EN-GB.
*
* This function requires the glossary entries for each dictionary to be
* provided as a dictionary of source-target terms. To create a glossary
* from a CSV file downloaded from the DeepL website, see
* {@link createMultilingualGlossaryWithCsv}.
*
* @param name user-defined name to attach to glossary.
* @param glossaryDicts the dictionaries of the glossary, see {@link MultilingualGlossaryDictionaryEntries}.
* @return {Promise<MultilingualGlossaryInfo>} object with details about the newly created glossary.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API
*/
async createMultilingualGlossary(
name: string,
glossaryDicts: MultilingualGlossaryDictionaryEntries[],
): Promise<MultilingualGlossaryInfo> {
if (!name) {
throw new ArgumentError('glossary name must not be empty');
}
const data = new URLSearchParams();
data.append('name', name);
appendDictionaryEntries(data, glossaryDicts);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'POST',
'/v3/glossaries',
{ data: data },
);
await checkStatusCode(statusCode, content);
return parseMultilingualGlossaryInfo(content);
}
/**
* Creates a multilingual glossary with the given name using entries from a CSV file.
* The CSV file must contain two columns: source terms and target terms.
* The glossary may be used in the translateText() functions.
*
* Only certain language pairs are supported. The available language pairs
* can be queried using getGlossaryLanguages(). Glossaries are not
* regional specific: a glossary with target language EN may be used to
* translate texts into both EN-US and EN-GB.
*
* @param name User-defined name to attach to the glossary.
* @param sourceLanguageCode Source language code for the glossary.
* @param targetLanguageCode Target language code for the glossary.
* @param csvContent String in CSV format containing the entries.
* @returns {Promise<MultilingualGlossaryInfo>} Object with details about the newly created glossary.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async createMultilingualGlossaryWithCsv(
name: string,
sourceLanguageCode: string,
targetLanguageCode: string,
csvContent: string,
): Promise<MultilingualGlossaryInfo> {
if (!name) {
throw new ArgumentError('Parameter "name" must not be empty');
}
if (!sourceLanguageCode) {
throw new ArgumentError('Parameter "sourceLanguageCode" must not be empty');
}
if (!targetLanguageCode) {
throw new ArgumentError('Parameter "targetLanguageCode" must not be empty');
}
if (!csvContent) {
throw new ArgumentError('Parameter "csvContent" must not be empty');
}
const data = new URLSearchParams();
data.append('name', name);
appendCsvDictionaryEntries(data, sourceLanguageCode, targetLanguageCode, csvContent);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'POST',
'/v3/glossaries',
{ data: data },
);
await checkStatusCode(statusCode, content);
return parseMultilingualGlossaryInfo(content);
}
/**
* Retrieves information about the glossary with the specified ID.
* This does not retrieve the glossary entries.
* @param glossaryId ID of glossary to retrieve.
* @returns {Promise<MultilingualGlossaryInfo>} object with details about the specified glossary.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async getMultilingualGlossary(glossaryId: string): Promise<MultilingualGlossaryInfo> {
if (!glossaryId) {
throw new ArgumentError('glossaryId must not be empty');
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
`/v3/glossaries/${glossaryId}`,
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
return parseMultilingualGlossaryInfo(content);
}
/**
* Retrieves the dictionary entries for a specific glossary and language pair.
*
* If the source and target language codes are specified, there should be at most one dictionary returned.
*
* @param glossary The ID of the glossary or MultilingualGlossaryInfo object to query.
* @param sourceLanguageCode Source language code of the dictionary.
* @param targetLanguageCode Target language code of the dictionary.
* @returns {Promise<MultilingualGlossaryDictionaryEntries>} Object containing the dictionary entries.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
* @throws {GlossaryNotFoundError} If no dictionary is found for the given source and target language codes.
*/
async getMultilingualGlossaryDictionaryEntries(
glossary: GlossaryId | MultilingualGlossaryInfo,
sourceLanguageCode: string,
targetLanguageCode: string,
): Promise<MultilingualGlossaryDictionaryEntries> {
if (!glossary) {
throw new ArgumentError('Parameter "glossary" must not be empty/null');
}
if (!sourceLanguageCode) {
throw new ArgumentError('Parameter "sourceLanguageCode" must not be empty');
}
if (!targetLanguageCode) {
throw new ArgumentError('Parameter "targetLanguageCode" must not be empty');
}
const glossaryId = extractGlossaryId(glossary);
const queryParams = new URLSearchParams();
queryParams.append('source_lang', sourceLanguageCode);
queryParams.append('target_lang', targetLanguageCode);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
`/v3/glossaries/${glossaryId}/entries`,
{ data: queryParams },
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
const response = JSON.parse(content) as MultilingualGlossaryDictionaryEntriesApiResponse;
const dictionaryEntriesList = parseMultilingualGlossaryDictionaryEntries(response);
if (!dictionaryEntriesList || dictionaryEntriesList.length === 0) {
throw new GlossaryNotFoundError('Glossary dictionary not found');
}
return dictionaryEntriesList[0];
}
/**
* Retrieves a list of all multilingual glossaries available for the authenticated user.
*
* @returns {Promise<MultilingualGlossaryInfo[]>} An array of objects containing details about each glossary.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async listMultilingualGlossaries(): Promise<MultilingualGlossaryInfo[]> {
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
'/v3/glossaries',
);
await checkStatusCode(statusCode, content);
const response = JSON.parse(content) as ListMultilingualGlossaryApiResponse;
return parseListMultilingualGlossaries(response);
}
/**
* Deletes the glossary with the specified ID or MultilingualGlossaryInfo object.
* @param glossary The ID of the glossary or MultilingualGlossaryInfo object to delete.
* @throws {Error} If the glossaryId is empty.
* @throws {DeepLError} If the glossary could not be deleted.
*/
async deleteMultilingualGlossary(
glossary: GlossaryId | MultilingualGlossaryInfo,
): Promise<void> {
const glossaryId = extractGlossaryId(glossary);
if (!glossaryId) {
throw new Error('glossaryId must not be empty');
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'DELETE',
`/v3/glossaries/${glossaryId}`,
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
}
/**
* Deletes a specific dictionary from a multilingual glossary based on the source and target language codes.
*
* @param glossary ID of the glossary or MultilingualGlossaryInfo object from which the dictionary will be deleted.
* @param sourceLanguageCode Source language code of the dictionary to delete.
* @param targetLanguageCode Target language code of the dictionary to delete.
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async deleteMultilingualGlossaryDictionary(
glossary: GlossaryId | MultilingualGlossaryInfo,
sourceLanguageCode: string,
targetLanguageCode: string,
): Promise<void> {
if (!glossary) {
throw new ArgumentError('Parameter "glossary" must not be empty/null');
}
if (!sourceLanguageCode) {
throw new ArgumentError('Parameter "sourceLanguageCode" must not be empty');
}
if (!targetLanguageCode) {
throw new ArgumentError('Parameter "targetLanguageCode" must not be empty');
}
const glossaryId = extractGlossaryId(glossary);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'DELETE',
`/v3/glossaries/${glossaryId}/dictionaries?source_lang=${sourceLanguageCode}&target_lang=${targetLanguageCode}`,
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
}
/**
* Replaces the dictionary entries for a specific source and target language pair in a multilingual glossary.
*
* @param glossary ID of the glossary or MultilingualGlossaryInfo object from which the dictionary will be deleted.
* @param sourceLanguageCode Source language code of the dictionary to replace.
* @param targetLanguageCode Target language code of the dictionary to replace.
* @param entries Dictionary entries to replace, formatted as a string in TSV format.
* @returns {Promise<MultilingualGlossaryDictionaryInfo>} Object containing details about the updated dictionary.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async replaceMultilingualGlossaryDictionary(
glossary: GlossaryId | MultilingualGlossaryInfo,
glossaryDict: MultilingualGlossaryDictionaryEntries,
): Promise<MultilingualGlossaryDictionaryInfo> {
if (!glossary) {
throw new ArgumentError('Parameter "glossary" must not be empty/null');
}
if (!glossaryDict) {
throw new ArgumentError('Parameter "glossaryDict" must not be null');
}
const glossaryId = extractGlossaryId(glossary);
const data = new URLSearchParams();
data.append('source_lang', glossaryDict.sourceLangCode);
data.append('target_lang', glossaryDict.targetLangCode);
data.append('entries', glossaryDict.entries.toTsv());
data.append('entries_format', 'tsv');
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'PUT',
`/v3/glossaries/${glossaryId}/dictionaries`,
{ data: data },
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
const response = JSON.parse(content) as MultilingualGlossaryDictionaryApiResponse;
return parseMultilingualGlossaryDictionaryInfo(response);
}
/**
* Replaces the dictionary entries for a specific source and target language pair in a multilingual glossary
* using entries from a CSV file.
*
* @param glossary ID of the glossary or MultilingualGlossaryInfo object from which the dictionary will be deleted.
* @param sourceLanguageCode Source language code of the dictionary to replace.
* @param targetLanguageCode Target language code of the dictionary to replace.
* @param csvContent String in CSV format containing the new entries.
* @returns {Promise<MultilingualGlossaryDictionaryInfo>} Object containing details about the updated dictionary.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async replaceMultilingualGlossaryDictionaryWithCsv(
glossary: GlossaryId | MultilingualGlossaryInfo,
sourceLanguageCode: string,
targetLanguageCode: string,
csvContent: string,
): Promise<MultilingualGlossaryDictionaryInfo> {
if (!glossary) {
throw new ArgumentError('Parameter "glossary" must not be empty/null');
}
if (!sourceLanguageCode) {
throw new ArgumentError('Parameter "sourceLanguageCode" must not be empty');
}
if (!targetLanguageCode) {
throw new ArgumentError('Parameter "targetLanguageCode" must not be empty');
}
if (!csvContent) {
throw new ArgumentError('Parameter "csvContent" must not be empty');
}
const glossaryId = extractGlossaryId(glossary);
const data = new URLSearchParams();
data.append('source_lang', sourceLanguageCode);
data.append('target_lang', targetLanguageCode);
data.append('entries', csvContent);
data.append('entries_format', 'csv');
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'PUT',
`/v3/glossaries/${glossaryId}/dictionaries`,
{ data: data },
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
const response = JSON.parse(content) as MultilingualGlossaryDictionaryApiResponse;
return parseMultilingualGlossaryDictionaryInfo(response);
}
/**
* Updates the name of a multilingual glossary.
*
* @param glossary ID of the glossary or MultilingualGlossaryInfo object from which the dictionary will be deleted.
* @param name New name for the glossary.
* @returns {Promise<MultilingualGlossaryInfo>} Object containing details about the updated glossary.
*
* @throws {ArgumentError} If the name is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async updateMultilingualGlossaryName(
glossary: GlossaryId | MultilingualGlossaryInfo,
name: string,
): Promise<MultilingualGlossaryInfo> {
if (!name) {
throw new ArgumentError('Parameter "name" must not be empty');
}
const glossaryId = extractGlossaryId(glossary);
const data = new URLSearchParams();
data.append('name', name);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'PATCH',
`/v3/glossaries/${glossaryId}`,
{ data: data },
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
return parseMultilingualGlossaryInfo(content);
}
/**
* Updates the dictionary entries for a specific source and target language pair in a multilingual glossary.
*
* @param glossary ID of the glossary or MultilingualGlossaryInfo object to update.
* @param glossaryDict The new or updated glossary dictionary.
* @returns {Promise<MultilingualGlossaryInfo>} Object containing details about the updated glossary.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async updateMultilingualGlossaryDictionary(
glossary: GlossaryId | MultilingualGlossaryInfo,
glossaryDict: MultilingualGlossaryDictionaryEntries,
): Promise<MultilingualGlossaryInfo> {
if (!glossary) {
throw new ArgumentError('Parameter "glossary" must not be empty/null');
}
if (!glossaryDict) {
throw new ArgumentError('Parameter "glossaryDict" must not be null');
}
const glossaryId = extractGlossaryId(glossary);
const data = new URLSearchParams();
appendDictionaryEntries(data, [glossaryDict]);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'PATCH',
`/v3/glossaries/${glossaryId}`,
{ data: data },
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
return parseMultilingualGlossaryInfo(content);
}
/**
* Updates the dictionary entries for a specific source and target language pair in a multilingual glossary
* using entries from a CSV file.
*
* @param glossary ID of the glossary or MultilingualGlossaryInfo object to update.
* @param sourceLanguageCode Source language code of the dictionary to update.
* @param targetLanguageCode Target language code of the dictionary to update.
* @param csvContent String in CSV format containing the new entries.
* @returns {Promise<MultilingualGlossaryInfo>} Object containing details about the updated glossary.
*
* @throws {ArgumentError} If any argument is invalid.
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async updateMultilingualGlossaryDictionaryWithCsv(
glossary: GlossaryId | MultilingualGlossaryInfo,
sourceLanguageCode: string,
targetLanguageCode: string,
csvContent: string,
): Promise<MultilingualGlossaryInfo> {
if (!glossary) {
throw new ArgumentError('Parameter "glossary" must not be empty/null');
}
if (!sourceLanguageCode) {
throw new ArgumentError('Parameter "sourceLanguageCode" must not be empty');
}
if (!targetLanguageCode) {
throw new ArgumentError('Parameter "targetLanguageCode" must not be empty');
}
if (!csvContent) {
throw new ArgumentError('Parameter "csvContent" must not be empty');
}
const glossaryId = extractGlossaryId(glossary);
const data = new URLSearchParams();
appendCsvDictionaryEntries(data, sourceLanguageCode, targetLanguageCode, csvContent);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'PATCH',
`/v3/glossaries/${glossaryId}`,
{ data: data },
);
await checkStatusCode(statusCode, content, true /* usingGlossary */);
return parseMultilingualGlossaryInfo(content);
}
/**
* Retrieves a list of all style rules available for the authenticated user.
*
* @param page: Page number for pagination, 0-indexed (optional).
* @param pageSize: Number of items per page (optional).
* @param detailed: Whether to include detailed configuration rules in the `configuredRules` property (optional).
* @returns {Promise<StyleRuleInfo[]>} An array of objects containing details about each style rule.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async getAllStyleRules(
page?: number,
pageSize?: number,
detailed?: boolean,
): Promise<StyleRuleInfo[]> {
const queryParams = new URLSearchParams();
if (page !== undefined) {
queryParams.append('page', String(page));
}
if (pageSize !== undefined) {
queryParams.append('page_size', String(pageSize));
}
if (detailed !== undefined) {
queryParams.append('detailed', String(detailed).toLowerCase());
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
'/v3/style_rules',
{ data: queryParams },
);
await checkStatusCode(statusCode, content);
return parseStyleRuleInfoList(content);
}
/**
* Retrieves a list of available translation memories. The maximum number of translation
* memories returned is controlled by pageSize (max 25).
*
* @param page: Page number for pagination, 0-indexed (optional).
* @param pageSize: Number of items per page (optional).
* @returns {Promise<TranslationMemoryInfo[]>} An array of objects containing details about each translation memory.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async listTranslationMemories(
page?: number,
pageSize?: number,
): Promise<TranslationMemoryInfo[]> {
const queryParams = new URLSearchParams();
if (page !== undefined) {
queryParams.append('page', String(page));
}
if (pageSize !== undefined) {
queryParams.append('page_size', String(pageSize));
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
'/v3/translation_memories',
{ data: queryParams },
);
await checkStatusCode(statusCode, content);
return parseTranslationMemoryInfoList(content);
}
/**
* Retrieves a single translation memory by ID.
*
* @param translationMemory: Translation memory ID, or TranslationMemoryInfo object.
* @returns {Promise<TranslationMemoryInfo>} Details of the translation memory.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async getTranslationMemory(
translationMemory: TranslationMemoryId | TranslationMemoryInfo,
): Promise<TranslationMemoryInfo> {
const translationMemoryId = extractTranslationMemoryId(translationMemory);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
`/v3/translation_memories/${translationMemoryId}`,
);
await checkStatusCode(statusCode, content);
return parseTranslationMemoryInfoJson(content);
}
/**
* Retrieves one page of the segments of a translation memory.
*
* Pagination is cursor-based: omit pageCursor on the first call, then pass the previous
* response's nextPageCursor to fetch the next page. An absent nextPageCursor means the last
* page has been returned. Note that segmentCount is the translation-memory total and is not
* reduced by filterText.
*
* @param translationMemory: Translation memory ID, or TranslationMemoryInfo object.
* @param options: Optional pagination and filtering options.
* @returns {Promise<TranslationMemorySegments>} One page of segments.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async listTranslationMemorySegments(
translationMemory: TranslationMemoryId | TranslationMemoryInfo,
options?: TranslationMemorySegmentsOptions,
): Promise<TranslationMemorySegments> {
const translationMemoryId = extractTranslationMemoryId(translationMemory);
const queryParams = new URLSearchParams();
if (options?.pageSize !== undefined) {
queryParams.append('page_size', String(options.pageSize));
}
if (options?.pageCursor !== undefined) {
queryParams.append('page_cursor', options.pageCursor);
}
if (options?.filterText !== undefined) {
queryParams.append('filter_text', options.filterText);
}
if (options?.filterCaseSensitive !== undefined) {
queryParams.append(
'filter_case_sensitive',
String(options.filterCaseSensitive).toLowerCase(),
);
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
`/v3/translation_memories/${translationMemoryId}/segments`,
{ data: queryParams },
);
await checkStatusCode(statusCode, content);
return parseTranslationMemorySegments(content);
}
/**
* Deletes the specified translation memory.
*
* @param translationMemory: Translation memory ID, or TranslationMemoryInfo object.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async deleteTranslationMemory(
translationMemory: TranslationMemoryId | TranslationMemoryInfo,
): Promise<void> {
const translationMemoryId = extractTranslationMemoryId(translationMemory);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'DELETE',
`/v3/translation_memories/${translationMemoryId}`,
);
await checkStatusCode(statusCode, content);
}
/**
* Creates an import job for a new translation memory.
*
* The job only declares the file; upload the TMX file itself to the returned upload URL with
* uploadTranslationMemoryFile(), then poll getTranslationMemoryJob() for the outcome. Use
* importTranslationMemoryFromFilepath() to do all three steps at once.
*
* @param fileName: Name of the TMX file to import, for example 'legal.tmx'.
* @param contentLength: Size of the TMX file in bytes.
* @param options: Optional contentType (defaults to 'application/xml') and displayName for the
* resulting translation memory (defaults to the file name).
* @returns {Promise<TranslationMemoryImport>} The job ID and upload URL.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async createTranslationMemoryImport(
fileName: string,
contentLength: number,
options?: { contentType?: string; displayName?: string },
): Promise<TranslationMemoryImport> {
if (!fileName) {
throw new ArgumentError('fileName must not be empty');
}
if (!(contentLength > 0)) {
throw new ArgumentError('contentLength must be greater than 0');
}
const sourceFile: Record<string, unknown> = {
file_name: fileName,
content_length: contentLength,
};
if (options?.contentType !== undefined) {
sourceFile.content_type = options.contentType;
}
const jsonBody: Record<string, unknown> = { source_file: sourceFile };
if (options?.displayName !== undefined) {
jsonBody.parameters = { display_name: options.displayName };
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'POST',
'/v3/translation_memories/import',
{ jsonBody },
);
await checkStatusCode(statusCode, content);
return parseTranslationMemoryImport(content);
}
/**
* Uploads a TMX file to the upload URL of an import job.
*
* The upload URL is a pre-signed storage URL outside of the DeepL API, so the authentication
* key is not sent with this request, and any 2xx response counts as success. The API detects
* the upload asynchronously, so the job keeps reporting 'awaiting_input' for a while afterwards
* before it starts processing.
*
* @param translationMemoryImport: The import returned by createTranslationMemoryImport(), or
* its upload URL.
* @param fileBuffer: TMX file content.
* @param contentType: MIME type of the file, which must match the content type declared when
* the import job was created. Defaults to 'application/xml'.
*
* @throws {DeepLError} If any error occurs while uploading the file.
*/
async uploadTranslationMemoryFile(
translationMemoryImport: string | TranslationMemoryImport,
fileBuffer: Buffer,
contentType = 'application/xml',
): Promise<void> {
const uploadUrl =
typeof translationMemoryImport === 'string'
? translationMemoryImport
: translationMemoryImport.uploadUrl;
if (!uploadUrl) {
throw new ArgumentError('uploadUrl must not be empty');
}
const { statusCode, content } = await this.storageHttpClient.sendRequestWithBackoff<string>(
'PUT',
uploadUrl,
{ rawBody: fileBuffer, headers: { 'Content-Type': contentType } },
);
if (statusCode < 200 || statusCode >= 300) {
throw new DeepLError(
`Error uploading translation memory file, HTTP status: ${statusCode}, content: ${content}`,
);
}
}
/**
* Creates an export job for a translation memory.
*
* Poll getTranslationMemoryJob() for the download URL of the exported TMX file. Use
* exportTranslationMemoryToFilepath() to do both steps and write the file at once.
*
* @param translationMemory: Translation memory ID, or TranslationMemoryInfo object.
* @returns {Promise<TranslationMemoryExport>} The job ID, and whether the API reused a
* previously completed export.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async createTranslationMemoryExport(
translationMemory: TranslationMemoryId | TranslationMemoryInfo,
): Promise<TranslationMemoryExport> {
const translationMemoryId = extractTranslationMemoryId(translationMemory);
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'POST',
`/v3/translation_memories/${translationMemoryId}/export`,
);
await checkStatusCode(statusCode, content);
// 200 means the API reused a previously completed export, 202 that it started a new one.
return parseTranslationMemoryExport(content, statusCode === 200);
}
/**
* Retrieves the status of a translation memory import or export job.
*
* @param jobId: ID of the job to query.
* @returns {Promise<TranslationMemoryJob>} The current status of the job.
*
* @throws {DeepLError} If any error occurs while communicating with the DeepL API.
*/
async getTranslationMemoryJob(jobId: string): Promise<TranslationMemoryJob> {
if (!jobId) {
throw new ArgumentError('jobId must not be empty');
}
const { statusCode, content } = await this.httpClient.sendRequestWithBackoff<string>(
'GET',
`/v3/translation_memories/jobs/${jobId}`,
);
await checkStatusCode(statusCode, content);
return parseTranslationMemoryJob(content);
}
/**
* Polls a translation memory job until it finishes, sleeping between requests, and resolves
* with the final status.
*
* Note that an import job keeps reporting 'awaiting_input' for a while after its file has been
* uploaded, because the API detects the upload asynchronously. That status is therefore polled
* through like any other non-terminal one. A job whose file is never uploaded does not finish
* on its own, so pass timeoutMs when that is a possibility.
*
* @param jobId: ID of the job to wait for.
* @param timeoutMs: (Optional) Maximum time to wait in milliseconds before rejecting. Note that
* this is not accurate to the millisecond, as the job is only polled every 5 seconds.
* @returns {Promise<TranslationMemoryJob>} The job once it has finished.
*
* @throws {DeepLError} If the job fails, the timeout is exceeded, or any error occurs while
* communicating with the DeepL API.
*/
async isTranslationMemoryJobComplete(
jobId: string,
timeoutMs?: number,
): Promise<TranslationMemoryJob> {
let job = await this.getTranslationMemoryJob(jobId);
const startTimeMs = Date.now();
while (!DeepLClient.isJobDone(job)) {
// The API always returns exactly one result with a known status. Anything else
// would never reach a terminal state, so fail closed instead of polling forever.
const status = job.results[0]?.status;
if (job.results.length === 0 || !DeepLClient.KNOWN_JOB_STATUSES.includes(status!)) {
throw new DeepLError(
`Translation memory job ${jobId} returned an unusable status: ${
status ?? 'none'
}`,
);
}
if (timeoutMs !== undefined && Date.now() - startTimeMs > timeoutMs) {
throw new DeepLError(
`Timeout of ${timeoutMs}ms exceeded for translation memory job`,
);
}
const secs = 5.0;
await timeout(secs * 1000);
logInfo(`Rechecking translation memory job status after sleeping for ${secs} seconds.`);
job = await this.getTranslationMemoryJob(jobId);
}
const result = job.results[0];
if (result !== undefined && (result.status === 'failed' || result.status === 'expired')) {
throw new DeepLError(result.errorMessage || `Job ${result.status}`);
}
return job;
}
/**
* Downloads the TMX file of a completed export job to the given output file path or stream.
*
* @param job: Completed export job carrying the download URL.
* @param outputFile: String containing output file path, or a WriteStream to store file data.
*
* @throws {DeepLError} If the job has no download URL, or any error occurs while downloading.
*/
async downloadTranslationMemoryExport(
job: TranslationMemoryJob,
outputFile: string | fs.WriteStream,
): Promise<void> {
const downloadUrl = job.results[0]?.downloadUrl;
if (!downloadUrl) {
throw new ArgumentError(
'translation memory export job has no download URL; it may not have completed yet',
);
}
// Streamed rather than buffered as text, mirroring downloadDocument(): a TMX export can
// be large, and decoding it to a string would both hold it all in memory and risk
// corrupting bytes that are not valid UTF-8.
const { statusCode, content } =
await this.storageHttpClient.sendRequestWithBackoff<IncomingMessage>(
'GET',
downloadUrl,
{},
true,
);
// Routed through checkStatusCode so the storage service's error body ends up in the
// message and the response stream is drained rather than left holding the socket.
await checkStatusCode(statusCode, content, false, true);
if (typeof outputFile === 'string') {
const fileStream = fs.createWriteStream(outputFile, { flags: 'wx' });
try {
await DeepLClient.pipeToStream(content, fileStream);
} catch (e) {
await new Promise((resolve) => fileStream.close(resolve));
// Never leave a truncated TMX behind: a caller that logs and continues would
// otherwise see a file that looks like a successful export. But 'wx' fails with
// EEXIST precisely to protect a file that was already there, so deleting on that
// error would destroy the very file the flag exists to guard.
if ((e as NodeJS.ErrnoException)?.code !== 'EEXIST') {
await fs.promises.unlink(outputFile).catch(() => undefined);
}
throw e;
}
return;
}
return DeepLClient.pipeToStream(content, outputFile);
}
/**
* Pipes a response stream to the given writable, rejecting if either side errors and
* destroying the other so neither is left dangling.
* @private
*/
private static pipeToStream(content: IncomingMessage, outputStream: fs.WriteStream) {
return new Promise<void>((resolve, reject) => {
const fail = (error: Error) => {
content.destroy();
outputStream.destroy();
reject(error);
};
content.on('error', fail);
outputStream.on('error', fail);
outputStream.on('finish', resolve);
content.pipe(outputStream);
});
}
/**