@translated/lara 1.7.0 → 1.7.2

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.
@@ -0,0 +1,57 @@
1
+ import type { LaraClient } from "./net";
2
+ import type { MultiPartFile } from "./net/client";
3
+ import type { TranslationStyle } from "./translator";
4
+ export type S3UploadFields = {
5
+ acl: string;
6
+ bucket: string;
7
+ key: string;
8
+ };
9
+ export declare enum DocumentStatus {
10
+ INITIALIZED = "initialized",// just been created
11
+ ANALYZING = "analyzing",// being analyzed for language detection and chars count
12
+ PAUSED = "paused",// paused after analysis, needs user confirm
13
+ READY = "ready",// ready to be translated
14
+ TRANSLATING = "translating",
15
+ TRANSLATED = "translated",
16
+ ERROR = "error"
17
+ }
18
+ export interface DocxExtractionParams {
19
+ extractComments?: boolean;
20
+ acceptRevisions?: boolean;
21
+ }
22
+ export type DocumentOptions = {
23
+ adaptTo?: string[];
24
+ glossaries?: string[];
25
+ noTrace?: boolean;
26
+ style?: TranslationStyle;
27
+ };
28
+ export type DocumentDownloadOptions = {
29
+ outputFormat?: string;
30
+ };
31
+ export type DocumentUploadOptions = DocumentOptions & {
32
+ password?: string;
33
+ extractionParams?: DocxExtractionParams;
34
+ };
35
+ export interface Document {
36
+ readonly id: string;
37
+ readonly status: DocumentStatus;
38
+ readonly source?: string;
39
+ readonly target: string;
40
+ readonly filename: string;
41
+ readonly createdAt: Date;
42
+ readonly updatedAt: Date;
43
+ readonly options?: DocumentOptions;
44
+ readonly translatedChars?: number;
45
+ readonly totalChars?: number;
46
+ readonly errorReason?: string;
47
+ }
48
+ export type DocumentTranslateOptions = DocumentUploadOptions & DocumentDownloadOptions;
49
+ export declare class Documents {
50
+ private readonly client;
51
+ private readonly s3Client;
52
+ constructor(client: LaraClient);
53
+ upload(file: MultiPartFile, filename: string, source: string | null, target: string, options?: DocumentUploadOptions): Promise<Document>;
54
+ status(id: string): Promise<Document>;
55
+ download(id: string, options?: DocumentDownloadOptions): Promise<Blob | Buffer>;
56
+ translate(file: MultiPartFile, filename: string, source: string | null, target: string, options?: DocumentTranslateOptions): Promise<Blob | Buffer>;
57
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Documents = exports.DocumentStatus = void 0;
7
+ const errors_1 = require("./errors");
8
+ const s3_1 = __importDefault(require("./net/s3"));
9
+ const to_snake_case_1 = __importDefault(require("./utils/to-snake-case"));
10
+ // biome-ignore format: keep comments aligned
11
+ var DocumentStatus;
12
+ (function (DocumentStatus) {
13
+ DocumentStatus["INITIALIZED"] = "initialized";
14
+ DocumentStatus["ANALYZING"] = "analyzing";
15
+ DocumentStatus["PAUSED"] = "paused";
16
+ DocumentStatus["READY"] = "ready";
17
+ DocumentStatus["TRANSLATING"] = "translating";
18
+ DocumentStatus["TRANSLATED"] = "translated";
19
+ DocumentStatus["ERROR"] = "error";
20
+ })(DocumentStatus || (exports.DocumentStatus = DocumentStatus = {}));
21
+ class Documents {
22
+ constructor(client) {
23
+ this.client = client;
24
+ this.s3Client = (0, s3_1.default)();
25
+ }
26
+ async upload(file, filename, source, target, options) {
27
+ const { url, fields } = await this.client.get(`/documents/upload-url`, { filename });
28
+ await this.s3Client.upload(url, fields, file);
29
+ const headers = (options === null || options === void 0 ? void 0 : options.noTrace) ? { "X-No-Trace": "true" } : {};
30
+ return this.client.post("/documents", {
31
+ source,
32
+ target,
33
+ s3key: fields.key,
34
+ adapt_to: options === null || options === void 0 ? void 0 : options.adaptTo,
35
+ glossaries: options === null || options === void 0 ? void 0 : options.glossaries,
36
+ style: options === null || options === void 0 ? void 0 : options.style,
37
+ password: options === null || options === void 0 ? void 0 : options.password,
38
+ extraction_params: (options === null || options === void 0 ? void 0 : options.extractionParams) ? (0, to_snake_case_1.default)(options.extractionParams) : undefined
39
+ }, undefined, headers);
40
+ }
41
+ async status(id) {
42
+ return await this.client.get(`/documents/${id}`);
43
+ }
44
+ async download(id, options) {
45
+ const { url } = await this.client.get(`/documents/${id}/download-url`, {
46
+ output_format: options === null || options === void 0 ? void 0 : options.outputFormat
47
+ });
48
+ return await this.s3Client.download(url);
49
+ }
50
+ async translate(file, filename, source, target, options) {
51
+ const uploadOptions = {
52
+ adaptTo: options === null || options === void 0 ? void 0 : options.adaptTo,
53
+ glossaries: options === null || options === void 0 ? void 0 : options.glossaries,
54
+ noTrace: options === null || options === void 0 ? void 0 : options.noTrace,
55
+ style: options === null || options === void 0 ? void 0 : options.style,
56
+ password: options === null || options === void 0 ? void 0 : options.password,
57
+ extractionParams: options === null || options === void 0 ? void 0 : options.extractionParams
58
+ };
59
+ const { id } = await this.upload(file, filename, source, target, uploadOptions);
60
+ const downloadOptions = (options === null || options === void 0 ? void 0 : options.outputFormat) ? { outputFormat: options.outputFormat } : undefined;
61
+ const pollingInterval = 2000;
62
+ const maxWaitTime = 1000 * 60 * 15; // 15 minutes
63
+ const start = Date.now();
64
+ while (Date.now() - start < maxWaitTime) {
65
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
66
+ const { status, errorReason } = await this.status(id);
67
+ if (status === DocumentStatus.TRANSLATED)
68
+ return await this.download(id, downloadOptions);
69
+ if (status === DocumentStatus.ERROR) {
70
+ throw new errors_1.LaraApiError(500, "DocumentError", errorReason);
71
+ }
72
+ }
73
+ throw new errors_1.TimeoutError();
74
+ }
75
+ }
76
+ exports.Documents = Documents;
@@ -0,0 +1,37 @@
1
+ import type { LaraClient } from "./net";
2
+ import type { MultiPartFile } from "./net/client";
3
+ export interface Glossary {
4
+ readonly id: string;
5
+ readonly name: string;
6
+ readonly ownerId: string;
7
+ readonly createdAt: Date;
8
+ readonly updatedAt: Date;
9
+ }
10
+ export interface GlossaryImport {
11
+ readonly id: string;
12
+ readonly begin: number;
13
+ readonly end: number;
14
+ readonly channel: number;
15
+ readonly size: number;
16
+ readonly progress: number;
17
+ }
18
+ export interface GlossaryCounts {
19
+ unidirectional?: Record<string, number>;
20
+ multidirectional?: number;
21
+ }
22
+ export type GlossaryImportCallback = (glossaryImport: GlossaryImport) => void;
23
+ export declare class Glossaries {
24
+ private readonly client;
25
+ private readonly pollingInterval;
26
+ constructor(client: LaraClient);
27
+ list(): Promise<Glossary[]>;
28
+ create(name: string): Promise<Glossary>;
29
+ get(id: string): Promise<Glossary | null>;
30
+ delete(id: string): Promise<Glossary>;
31
+ update(id: string, name: string): Promise<Glossary>;
32
+ importCsv(id: string, csv: MultiPartFile, gzip?: boolean): Promise<GlossaryImport>;
33
+ getImportStatus(id: string): Promise<GlossaryImport>;
34
+ waitForImport(gImport: GlossaryImport, updateCallback?: GlossaryImportCallback, maxWaitTime?: number): Promise<GlossaryImport>;
35
+ counts(id: string): Promise<GlossaryCounts>;
36
+ export(id: string, contentType: "csv/table-uni", source?: string): Promise<string>;
37
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Glossaries = void 0;
4
+ const errors_1 = require("./errors");
5
+ class Glossaries {
6
+ constructor(client) {
7
+ this.client = client;
8
+ this.pollingInterval = 2000;
9
+ }
10
+ async list() {
11
+ return await this.client.get("/glossaries");
12
+ }
13
+ async create(name) {
14
+ return await this.client.post("/glossaries", { name });
15
+ }
16
+ async get(id) {
17
+ try {
18
+ return await this.client.get(`/glossaries/${id}`);
19
+ }
20
+ catch (e) {
21
+ if (e instanceof errors_1.LaraApiError && e.statusCode === 404) {
22
+ return null;
23
+ }
24
+ throw e;
25
+ }
26
+ }
27
+ async delete(id) {
28
+ return await this.client.delete(`/glossaries/${id}`);
29
+ }
30
+ async update(id, name) {
31
+ return await this.client.put(`/glossaries/${id}`, { name });
32
+ }
33
+ async importCsv(id, csv, gzip = false) {
34
+ return await this.client.post(`/glossaries/${id}/import`, {
35
+ compression: gzip ? "gzip" : undefined
36
+ }, {
37
+ csv
38
+ });
39
+ }
40
+ async getImportStatus(id) {
41
+ return await this.client.get(`/glossaries/imports/${id}`);
42
+ }
43
+ async waitForImport(gImport, updateCallback, maxWaitTime) {
44
+ const start = Date.now();
45
+ while (gImport.progress < 1.0) {
46
+ if (maxWaitTime && Date.now() - start > maxWaitTime)
47
+ throw new errors_1.TimeoutError();
48
+ await new Promise((resolve) => setTimeout(resolve, this.pollingInterval));
49
+ gImport = await this.getImportStatus(gImport.id);
50
+ if (updateCallback)
51
+ updateCallback(gImport);
52
+ }
53
+ return gImport;
54
+ }
55
+ async counts(id) {
56
+ return await this.client.get(`/glossaries/${id}/counts`);
57
+ }
58
+ async export(id, contentType, source) {
59
+ return await this.client.get(`/glossaries/${id}/export`, {
60
+ content_type: contentType,
61
+ source
62
+ });
63
+ }
64
+ }
65
+ exports.Glossaries = Glossaries;
package/lib/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { Credentials } from "./credentials";
2
+ export { Document, DocumentDownloadOptions, DocumentStatus, Documents, DocumentTranslateOptions, DocumentUploadOptions } from "./documents";
2
3
  export { LaraApiError, LaraError, TimeoutError } from "./errors";
4
+ export { Glossaries, GlossaryImport, GlossaryImportCallback } from "./glossaries";
5
+ export { Memories, Memory, MemoryImport, MemoryImportCallback } from "./memories";
3
6
  export { MultiPartFile } from "./net/client";
4
- export { version } from "./sdk-version";
5
- export { Document, DocumentDownloadOptions, DocumentStatus, DocumentUploadOptions, Memory, MemoryImport, NGGlossaryMatch, NGMemoryMatch, TextBlock, TextResult, DetectResult } from "./translator/models";
6
- export { Documents, DocumentTranslateOptions, Memories, MemoryImportCallback, TranslateOptions, Translator, TranslatorOptions } from "./translator/translator";
7
+ export { DetectResult, NGGlossaryMatch, NGMemoryMatch, TextBlock, TextResult, TranslateOptions, Translator, TranslatorOptions } from "./translator";
8
+ export { version } from "./utils/sdk-version";
package/lib/index.js CHANGED
@@ -1,17 +1,20 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Translator = exports.Memories = exports.Documents = exports.DocumentStatus = exports.version = exports.TimeoutError = exports.LaraError = exports.LaraApiError = exports.Credentials = void 0;
3
+ exports.version = exports.Translator = exports.Memories = exports.Glossaries = exports.TimeoutError = exports.LaraError = exports.LaraApiError = exports.Documents = exports.DocumentStatus = exports.Credentials = void 0;
4
4
  var credentials_1 = require("./credentials");
5
5
  Object.defineProperty(exports, "Credentials", { enumerable: true, get: function () { return credentials_1.Credentials; } });
6
+ var documents_1 = require("./documents");
7
+ Object.defineProperty(exports, "DocumentStatus", { enumerable: true, get: function () { return documents_1.DocumentStatus; } });
8
+ Object.defineProperty(exports, "Documents", { enumerable: true, get: function () { return documents_1.Documents; } });
6
9
  var errors_1 = require("./errors");
7
10
  Object.defineProperty(exports, "LaraApiError", { enumerable: true, get: function () { return errors_1.LaraApiError; } });
8
11
  Object.defineProperty(exports, "LaraError", { enumerable: true, get: function () { return errors_1.LaraError; } });
9
12
  Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_1.TimeoutError; } });
10
- var sdk_version_1 = require("./sdk-version");
11
- Object.defineProperty(exports, "version", { enumerable: true, get: function () { return sdk_version_1.version; } });
12
- var models_1 = require("./translator/models");
13
- Object.defineProperty(exports, "DocumentStatus", { enumerable: true, get: function () { return models_1.DocumentStatus; } });
14
- var translator_1 = require("./translator/translator");
15
- Object.defineProperty(exports, "Documents", { enumerable: true, get: function () { return translator_1.Documents; } });
16
- Object.defineProperty(exports, "Memories", { enumerable: true, get: function () { return translator_1.Memories; } });
13
+ var glossaries_1 = require("./glossaries");
14
+ Object.defineProperty(exports, "Glossaries", { enumerable: true, get: function () { return glossaries_1.Glossaries; } });
15
+ var memories_1 = require("./memories");
16
+ Object.defineProperty(exports, "Memories", { enumerable: true, get: function () { return memories_1.Memories; } });
17
+ var translator_1 = require("./translator");
17
18
  Object.defineProperty(exports, "Translator", { enumerable: true, get: function () { return translator_1.Translator; } });
19
+ var sdk_version_1 = require("./utils/sdk-version");
20
+ Object.defineProperty(exports, "version", { enumerable: true, get: function () { return sdk_version_1.version; } });
@@ -0,0 +1,38 @@
1
+ import type { LaraClient } from "./net";
2
+ import type { MultiPartFile } from "./net/client";
3
+ export interface Memory {
4
+ readonly id: string;
5
+ readonly createdAt: Date;
6
+ readonly updatedAt: Date;
7
+ readonly sharedAt: Date;
8
+ readonly name: string;
9
+ readonly externalId?: string;
10
+ readonly secret?: string;
11
+ readonly ownerId: string;
12
+ readonly collaboratorsCount: number;
13
+ }
14
+ export interface MemoryImport {
15
+ readonly id: string;
16
+ readonly begin: number;
17
+ readonly end: number;
18
+ readonly channel: number;
19
+ readonly size: number;
20
+ readonly progress: number;
21
+ }
22
+ export type MemoryImportCallback = (memoryImport: MemoryImport) => void;
23
+ export declare class Memories {
24
+ private readonly client;
25
+ private readonly pollingInterval;
26
+ constructor(client: LaraClient);
27
+ list(): Promise<Memory[]>;
28
+ create(name: string, externalId?: string): Promise<Memory>;
29
+ get(id: string): Promise<Memory | null>;
30
+ delete(id: string): Promise<Memory>;
31
+ update(id: string, name: string): Promise<Memory>;
32
+ connect<T extends string | string[]>(ids: T): Promise<T extends string ? Memory : Memory[]>;
33
+ importTmx(id: string, tmx: MultiPartFile, gzip?: boolean): Promise<MemoryImport>;
34
+ addTranslation(id: string | string[], source: string, target: string, sentence: string, translation: string, tuid?: string, sentenceBefore?: string, sentenceAfter?: string, headers?: Record<string, string>): Promise<MemoryImport>;
35
+ deleteTranslation(id: string | string[], source: string, target: string, sentence?: string, translation?: string, tuid?: string, sentenceBefore?: string, sentenceAfter?: string): Promise<MemoryImport>;
36
+ getImportStatus(id: string): Promise<MemoryImport>;
37
+ waitForImport(mImport: MemoryImport, updateCallback?: MemoryImportCallback, maxWaitTime?: number): Promise<MemoryImport>;
38
+ }
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Memories = void 0;
4
+ const errors_1 = require("./errors");
5
+ class Memories {
6
+ constructor(client) {
7
+ this.client = client;
8
+ this.pollingInterval = 2000;
9
+ }
10
+ async list() {
11
+ return await this.client.get("/memories");
12
+ }
13
+ async create(name, externalId) {
14
+ return await this.client.post("/memories", {
15
+ name,
16
+ external_id: externalId
17
+ });
18
+ }
19
+ async get(id) {
20
+ try {
21
+ return await this.client.get(`/memories/${id}`);
22
+ }
23
+ catch (e) {
24
+ if (e instanceof errors_1.LaraApiError && e.statusCode === 404) {
25
+ return null;
26
+ }
27
+ throw e;
28
+ }
29
+ }
30
+ async delete(id) {
31
+ return await this.client.delete(`/memories/${id}`);
32
+ }
33
+ async update(id, name) {
34
+ return await this.client.put(`/memories/${id}`, { name });
35
+ }
36
+ async connect(ids) {
37
+ const memories = await this.client.post("/memories/connect", {
38
+ ids: Array.isArray(ids) ? ids : [ids]
39
+ });
40
+ return (Array.isArray(ids) ? memories : memories[0]);
41
+ }
42
+ async importTmx(id, tmx, gzip = false) {
43
+ return await this.client.post(`/memories/${id}/import`, {
44
+ compression: gzip ? "gzip" : undefined
45
+ }, {
46
+ tmx
47
+ });
48
+ }
49
+ async addTranslation(id, source, target, sentence, translation, tuid, sentenceBefore, sentenceAfter, headers) {
50
+ const body = {
51
+ source,
52
+ target,
53
+ sentence,
54
+ translation,
55
+ tuid,
56
+ sentence_before: sentenceBefore,
57
+ sentence_after: sentenceAfter
58
+ };
59
+ if (Array.isArray(id)) {
60
+ body.ids = id;
61
+ return await this.client.put("/memories/content", body, undefined, headers);
62
+ }
63
+ else {
64
+ return await this.client.put(`/memories/${id}/content`, body, undefined, headers);
65
+ }
66
+ }
67
+ async deleteTranslation(id, source, target, sentence, translation, tuid, sentenceBefore, sentenceAfter) {
68
+ const body = {
69
+ source,
70
+ target,
71
+ sentence,
72
+ translation,
73
+ tuid,
74
+ sentence_before: sentenceBefore,
75
+ sentence_after: sentenceAfter
76
+ };
77
+ if (Array.isArray(id)) {
78
+ body.ids = id;
79
+ return await this.client.delete("/memories/content", body);
80
+ }
81
+ else {
82
+ return await this.client.delete(`/memories/${id}/content`, body);
83
+ }
84
+ }
85
+ async getImportStatus(id) {
86
+ return await this.client.get(`/memories/imports/${id}`);
87
+ }
88
+ async waitForImport(mImport, updateCallback, maxWaitTime) {
89
+ const start = Date.now();
90
+ while (mImport.progress < 1.0) {
91
+ if (maxWaitTime && Date.now() - start > maxWaitTime)
92
+ throw new errors_1.TimeoutError();
93
+ await new Promise((resolve) => setTimeout(resolve, this.pollingInterval));
94
+ mImport = await this.getImportStatus(mImport.id);
95
+ if (updateCallback)
96
+ updateCallback(mImport);
97
+ }
98
+ return mImport;
99
+ }
100
+ }
101
+ exports.Memories = Memories;
@@ -4,5 +4,6 @@ export declare class BrowserLaraClient extends LaraClient {
4
4
  private readonly baseUrl;
5
5
  constructor(baseUrl: BaseURL, accessKeyId: string, accessKeySecret: string);
6
6
  protected send(path: string, headers: Record<string, string>, body?: Record<string, any>): Promise<ClientResponse>;
7
+ protected sendAndGetStream(path: string, headers: Record<string, string>, body?: Record<string, any>): AsyncGenerator<ClientResponse>;
7
8
  protected wrapMultiPartFile(file: MultiPartFile): File;
8
9
  }
@@ -53,6 +53,83 @@ class BrowserLaraClient extends client_1.LaraClient {
53
53
  }
54
54
  return { statusCode: response.status, body: await response.json() };
55
55
  }
56
+ async *sendAndGetStream(path, headers, body) {
57
+ let requestBody;
58
+ if (body) {
59
+ if (headers["Content-Type"] === "multipart/form-data") {
60
+ delete headers["Content-Type"]; // browser will set it automatically
61
+ const formBody = new FormData();
62
+ for (const [key, value] of Object.entries(body)) {
63
+ if (!value)
64
+ continue;
65
+ if (Array.isArray(value)) {
66
+ for (const v of value)
67
+ formBody.append(key, v);
68
+ }
69
+ else {
70
+ formBody.append(key, value);
71
+ }
72
+ }
73
+ requestBody = formBody;
74
+ }
75
+ else {
76
+ requestBody = JSON.stringify(body, undefined, 0);
77
+ }
78
+ }
79
+ const response = await fetch(this.baseUrl + path, {
80
+ headers,
81
+ method: "POST",
82
+ body: requestBody
83
+ });
84
+ if (!response.body) {
85
+ throw new Error("Response body is not available for streaming");
86
+ }
87
+ const reader = response.body.getReader();
88
+ const decoder = new TextDecoder();
89
+ let buffer = "";
90
+ try {
91
+ while (true) {
92
+ const readResult = await reader.read();
93
+ const { done, value } = readResult;
94
+ if (done) {
95
+ // Process any remaining data in buffer
96
+ if (buffer.trim()) {
97
+ try {
98
+ const json = JSON.parse(buffer);
99
+ yield {
100
+ statusCode: json.status || response.status,
101
+ body: json.data || json
102
+ };
103
+ }
104
+ catch (_e) {
105
+ // Skip invalid JSON
106
+ }
107
+ }
108
+ break;
109
+ }
110
+ buffer += decoder.decode(value, { stream: true });
111
+ const lines = buffer.split("\n");
112
+ buffer = lines.pop() || ""; // Keep incomplete line in buffer
113
+ for (const line of lines) {
114
+ if (line.trim()) {
115
+ try {
116
+ const json = JSON.parse(line);
117
+ yield {
118
+ statusCode: json.status || response.status,
119
+ body: json.data || json
120
+ };
121
+ }
122
+ catch (_e) {
123
+ // Skip invalid JSON lines
124
+ }
125
+ }
126
+ }
127
+ }
128
+ }
129
+ finally {
130
+ reader.releaseLock();
131
+ }
132
+ }
56
133
  wrapMultiPartFile(file) {
57
134
  if (file instanceof File)
58
135
  return file;
@@ -25,10 +25,13 @@ export declare abstract class LaraClient {
25
25
  get<T>(path: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<T>;
26
26
  delete<T>(path: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<T>;
27
27
  post<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>): Promise<T>;
28
+ postAndGetStream<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>): AsyncGenerator<T>;
28
29
  put<T>(path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>): Promise<T>;
30
+ protected requestStream<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>): AsyncGenerator<T>;
29
31
  protected request<T>(method: HttpMethod, path: string, body?: Record<string, any>, files?: Record<string, MultiPartFile>, headers?: Record<string, string>): Promise<T>;
30
32
  private sign;
31
33
  protected abstract send(path: string, headers: Record<string, string>, body?: Record<string, any>): Promise<ClientResponse>;
34
+ protected abstract sendAndGetStream(path: string, headers: Record<string, string>, body?: Record<string, any>): AsyncGenerator<ClientResponse>;
32
35
  protected abstract wrapMultiPartFile(file: MultiPartFile): any;
33
36
  }
34
37
  export {};
package/lib/net/client.js CHANGED
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.LaraClient = void 0;
7
7
  const crypto_1 = __importDefault(require("../crypto"));
8
8
  const errors_1 = require("../errors");
9
- const sdk_version_1 = require("../sdk-version");
9
+ const sdk_version_1 = require("../utils/sdk-version");
10
10
  function parseContent(content) {
11
11
  if (content === undefined || content === null)
12
12
  return content;
@@ -49,9 +49,53 @@ class LaraClient {
49
49
  post(path, body, files, headers) {
50
50
  return this.request("POST", path, body, files, headers);
51
51
  }
52
+ async *postAndGetStream(path, body, files, headers) {
53
+ for await (const chunk of this.requestStream("POST", path, body, files, headers)) {
54
+ yield chunk;
55
+ }
56
+ }
52
57
  put(path, body, files, headers) {
53
58
  return this.request("PUT", path, body, files, headers);
54
59
  }
60
+ async *requestStream(method, path, body, files, headers) {
61
+ if (!path.startsWith("/"))
62
+ path = `/${path}`;
63
+ const _headers = {
64
+ "X-HTTP-Method-Override": method,
65
+ "X-Lara-Date": new Date().toUTCString(),
66
+ "X-Lara-SDK-Name": "lara-node",
67
+ "X-Lara-SDK-Version": sdk_version_1.version,
68
+ ...this.extraHeaders,
69
+ ...headers
70
+ };
71
+ if (body) {
72
+ body = Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined && v !== null));
73
+ if (Object.keys(body).length === 0)
74
+ body = undefined;
75
+ if (body) {
76
+ const jsonBody = JSON.stringify(body, undefined, 0);
77
+ _headers["Content-MD5"] = await this.crypto.digest(jsonBody);
78
+ }
79
+ }
80
+ let requestBody;
81
+ if (files) {
82
+ // validate files
83
+ for (const [key, file] of Object.entries(files))
84
+ files[key] = this.wrapMultiPartFile(file);
85
+ _headers["Content-Type"] = "multipart/form-data";
86
+ requestBody = Object.assign({}, files, body);
87
+ }
88
+ else {
89
+ _headers["Content-Type"] = "application/json";
90
+ if (body)
91
+ requestBody = body;
92
+ }
93
+ const signature = await this.sign(method, path, _headers);
94
+ _headers.Authorization = `Lara ${this.accessKeyId}:${signature}`;
95
+ for await (const chunk of this.sendAndGetStream(path, _headers, requestBody)) {
96
+ yield parseContent(chunk.body.content);
97
+ }
98
+ }
55
99
  async request(method, path, body, files, headers) {
56
100
  if (!path.startsWith("/"))
57
101
  path = `/${path}`;
@@ -1,3 +1,3 @@
1
1
  import type { LaraClient } from "./client";
2
2
  export { LaraClient } from "./client";
3
- export default function create(accessKeyId: string, accessKeySecret: string, baseUrl?: string): LaraClient;
3
+ export default function create(accessKeyId: string, accessKeySecret: string, baseUrl?: string, keepAlive?: boolean): LaraClient;
package/lib/net/index.js CHANGED
@@ -7,7 +7,7 @@ const node_client_1 = require("./node-client");
7
7
  var client_1 = require("./client");
8
8
  Object.defineProperty(exports, "LaraClient", { enumerable: true, get: function () { return client_1.LaraClient; } });
9
9
  const DEFAULT_BASE_URL = "https://api.laratranslate.com";
10
- function create(accessKeyId, accessKeySecret, baseUrl) {
10
+ function create(accessKeyId, accessKeySecret, baseUrl, keepAlive) {
11
11
  const url = new URL(baseUrl || DEFAULT_BASE_URL);
12
12
  if (url.protocol !== "https:" && url.protocol !== "http:")
13
13
  throw new TypeError(`Invalid URL (protocol): ${url.protocol}`);
@@ -19,5 +19,5 @@ function create(accessKeyId, accessKeySecret, baseUrl) {
19
19
  if (typeof window !== "undefined")
20
20
  return new browser_client_1.BrowserLaraClient(parsedURL, accessKeyId, accessKeySecret);
21
21
  else
22
- return new node_client_1.NodeLaraClient(parsedURL, accessKeyId, accessKeySecret);
22
+ return new node_client_1.NodeLaraClient(parsedURL, accessKeyId, accessKeySecret, keepAlive !== null && keepAlive !== void 0 ? keepAlive : true);
23
23
  }
@@ -4,7 +4,8 @@ import { type BaseURL, type ClientResponse, LaraClient, type MultiPartFile } fro
4
4
  export declare class NodeLaraClient extends LaraClient {
5
5
  private readonly baseUrl;
6
6
  private readonly agent;
7
- constructor(baseUrl: BaseURL, accessKeyId: string, accessKeySecret: string);
7
+ constructor(baseUrl: BaseURL, accessKeyId: string, accessKeySecret: string, keepAlive?: boolean);
8
8
  protected send(path: string, headers: Record<string, string>, body?: Record<string, any>): Promise<ClientResponse>;
9
+ protected sendAndGetStream(path: string, headers: Record<string, string>, body?: Record<string, any>): AsyncGenerator<ClientResponse>;
9
10
  protected wrapMultiPartFile(file: MultiPartFile): Readable;
10
11
  }