@molecule/api-ai-translation-deepl 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +115 -0
- package/dist/browser-guard.d.ts +2 -0
- package/dist/browser-guard.d.ts.map +1 -0
- package/dist/browser-guard.js +18 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +35 -0
- package/dist/provider.d.ts +24 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +277 -0
- package/dist/secrets.d.ts +16 -0
- package/dist/secrets.d.ts.map +1 -0
- package/dist/secrets.js +24 -0
- package/dist/types.d.ts +23 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/package.json +39 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work.
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the
|
|
45
|
+
original version of the Work and any modifications or additions
|
|
46
|
+
to that Work, that is intentionally submitted to the Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or
|
|
48
|
+
Legal Entity authorized to submit on behalf of the copyright owner.
|
|
49
|
+
|
|
50
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
51
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
52
|
+
subsequently incorporated within the Work.
|
|
53
|
+
|
|
54
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
55
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
56
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
57
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
58
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
59
|
+
Work and such Derivative Works in Source or Object form.
|
|
60
|
+
|
|
61
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
62
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
63
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
64
|
+
patent license to make, have made, use, offer to sell, sell, import,
|
|
65
|
+
and otherwise transfer the Work.
|
|
66
|
+
|
|
67
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
68
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
69
|
+
modifications, and in Source or Object form, provided that You
|
|
70
|
+
meet the following conditions:
|
|
71
|
+
|
|
72
|
+
(a) You must give any other recipients of the Work or
|
|
73
|
+
Derivative Works a copy of this License; and
|
|
74
|
+
|
|
75
|
+
(b) You must cause any modified files to carry prominent notices
|
|
76
|
+
stating that You changed the files; and
|
|
77
|
+
|
|
78
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
79
|
+
that You distribute, all copyright, patent, trademark, and
|
|
80
|
+
attribution notices from the Source form of the Work,
|
|
81
|
+
excluding those notices that do not pertain to any part of
|
|
82
|
+
the Derivative Works; and
|
|
83
|
+
|
|
84
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
85
|
+
distribution, then any Derivative Works that You distribute must
|
|
86
|
+
include a readable copy of the attribution notices contained
|
|
87
|
+
within such NOTICE file.
|
|
88
|
+
|
|
89
|
+
5. Submission of Contributions.
|
|
90
|
+
|
|
91
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
92
|
+
names, trademarks, service marks, or product names of the Licensor.
|
|
93
|
+
|
|
94
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
95
|
+
agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
|
|
96
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
|
|
97
|
+
|
|
98
|
+
8. Limitation of Liability. In no event and under no legal theory shall
|
|
99
|
+
any Contributor be liable to You for damages.
|
|
100
|
+
|
|
101
|
+
9. Accepting Warranty or Additional Liability.
|
|
102
|
+
|
|
103
|
+
Copyright 2026 Molecule Dev, Inc.
|
|
104
|
+
|
|
105
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
106
|
+
you may not use this file except in compliance with the License.
|
|
107
|
+
You may obtain a copy of the License at
|
|
108
|
+
|
|
109
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
110
|
+
|
|
111
|
+
Unless required by applicable law or agreed to in writing, software
|
|
112
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
113
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
114
|
+
See the License for the specific language governing permissions and
|
|
115
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser guard — `@molecule/api-ai-translation-deepl` is SERVER-ONLY.
|
|
3
|
+
*
|
|
4
|
+
* Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
|
|
5
|
+
* Evaluating a server package in a browser bundle is always an import-graph mistake
|
|
6
|
+
* (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
|
|
7
|
+
* ("Buffer is not defined") far from the culprit. Throwing here names the package and
|
|
8
|
+
* the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
|
|
9
|
+
* unaffected: the throw requires browser globals AND the absence of a node runtime.
|
|
10
|
+
*/
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
|
|
13
|
+
throw new Error('@molecule/api-ai-translation-deepl is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
|
|
14
|
+
'from server code (a server route/function or your API), or dynamic-import it inside ' +
|
|
15
|
+
'the server handler — never from components or shared client modules, and never ' +
|
|
16
|
+
'polyfill Buffer/process to silence this.');
|
|
17
|
+
}
|
|
18
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL translation provider for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Implements the full `@molecule/api-ai-translation` contract (`translate`,
|
|
5
|
+
* `getSupportedLanguages`, `getUsage`) over the DeepL REST API, auto-batching
|
|
6
|
+
* large inputs (50 texts per request, DeepL's limit).
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { setProvider, requireProvider } from '@molecule/api-ai-translation'
|
|
11
|
+
* import { provider } from '@molecule/api-ai-translation-deepl'
|
|
12
|
+
*
|
|
13
|
+
* setProvider(provider) // at startup — lazy; reads DEEPL_API_KEY on first use
|
|
14
|
+
*
|
|
15
|
+
* const { translations } = await requireProvider().translate({
|
|
16
|
+
* text: 'Hello, world!',
|
|
17
|
+
* targetLang: 'DE',
|
|
18
|
+
* })
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
|
|
23
|
+
* `setProvider(createProvider(config?))` to pass explicit config. Use the core's
|
|
24
|
+
* `setProvider`, NOT `bond('ai-translation', …)`.
|
|
25
|
+
* - Config: `DEEPL_API_KEY` (required; free keys end in `:fx` and auto-route to
|
|
26
|
+
* `https://api-free.deepl.com`, pro keys to `https://api.deepl.com`); `DEEPL_BASE_URL`
|
|
27
|
+
* (optional) overrides the endpoint outright — it deliberately wins over the key-shape
|
|
28
|
+
* heuristic so credential brokers/gateways work with either key type.
|
|
29
|
+
*
|
|
30
|
+
* @module
|
|
31
|
+
*/
|
|
32
|
+
export * from './browser-guard.js';
|
|
33
|
+
export * from './provider.js';
|
|
34
|
+
export * from './secrets.js';
|
|
35
|
+
export * from './types.js';
|
|
36
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,YAAY,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL translation provider for molecule.dev.
|
|
3
|
+
*
|
|
4
|
+
* Implements the full `@molecule/api-ai-translation` contract (`translate`,
|
|
5
|
+
* `getSupportedLanguages`, `getUsage`) over the DeepL REST API, auto-batching
|
|
6
|
+
* large inputs (50 texts per request, DeepL's limit).
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```typescript
|
|
10
|
+
* import { setProvider, requireProvider } from '@molecule/api-ai-translation'
|
|
11
|
+
* import { provider } from '@molecule/api-ai-translation-deepl'
|
|
12
|
+
*
|
|
13
|
+
* setProvider(provider) // at startup — lazy; reads DEEPL_API_KEY on first use
|
|
14
|
+
*
|
|
15
|
+
* const { translations } = await requireProvider().translate({
|
|
16
|
+
* text: 'Hello, world!',
|
|
17
|
+
* targetLang: 'DE',
|
|
18
|
+
* })
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* - **Wiring**: bond the lazy `provider` export once — `setProvider(provider)` — or
|
|
23
|
+
* `setProvider(createProvider(config?))` to pass explicit config. Use the core's
|
|
24
|
+
* `setProvider`, NOT `bond('ai-translation', …)`.
|
|
25
|
+
* - Config: `DEEPL_API_KEY` (required; free keys end in `:fx` and auto-route to
|
|
26
|
+
* `https://api-free.deepl.com`, pro keys to `https://api.deepl.com`); `DEEPL_BASE_URL`
|
|
27
|
+
* (optional) overrides the endpoint outright — it deliberately wins over the key-shape
|
|
28
|
+
* heuristic so credential brokers/gateways work with either key type.
|
|
29
|
+
*
|
|
30
|
+
* @module
|
|
31
|
+
*/
|
|
32
|
+
export * from './browser-guard.js';
|
|
33
|
+
export * from './provider.js';
|
|
34
|
+
export * from './secrets.js';
|
|
35
|
+
export * from './types.js';
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL implementation of AITranslationProvider.
|
|
3
|
+
*
|
|
4
|
+
* Uses the DeepL REST API v2 to translate text, list supported languages,
|
|
5
|
+
* and retrieve usage statistics. Supports both free and pro API keys with
|
|
6
|
+
* automatic base URL detection and retry with exponential backoff.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import './secrets.js';
|
|
11
|
+
import type { AITranslationProvider } from '@molecule/api-ai-translation';
|
|
12
|
+
import type { DeeplConfig } from './types.js';
|
|
13
|
+
/**
|
|
14
|
+
* Creates a DeepL translation provider instance.
|
|
15
|
+
*
|
|
16
|
+
* @param config - DeepL-specific configuration (API key, base URL, defaults).
|
|
17
|
+
* @returns An `AITranslationProvider` backed by the DeepL REST API.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createProvider(config?: DeeplConfig): AITranslationProvider;
|
|
20
|
+
/**
|
|
21
|
+
* The provider implementation.
|
|
22
|
+
*/
|
|
23
|
+
export declare const provider: AITranslationProvider;
|
|
24
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EACV,qBAAqB,EAKtB,MAAM,8BAA8B,CAAA;AAErC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAyT7C;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,qBAAqB,CAE1E;AAID;;GAEG;AACH,eAAO,MAAM,QAAQ,EAAE,qBAUrB,CAAA"}
|
package/dist/provider.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL implementation of AITranslationProvider.
|
|
3
|
+
*
|
|
4
|
+
* Uses the DeepL REST API v2 to translate text, list supported languages,
|
|
5
|
+
* and retrieve usage statistics. Supports both free and pro API keys with
|
|
6
|
+
* automatic base URL detection and retry with exponential backoff.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
// Side-effect import: registers this bond's secret definitions so the
|
|
11
|
+
// runtime registry is populated even when provider.js is imported directly
|
|
12
|
+
// (not through the package barrel).
|
|
13
|
+
import './secrets.js';
|
|
14
|
+
/** HTTP status codes that are retryable. */
|
|
15
|
+
const RETRYABLE_STATUS_CODES = new Set([429, 503, 529]);
|
|
16
|
+
/** Maximum number of retry attempts for retryable errors. */
|
|
17
|
+
const MAX_RETRIES = 3;
|
|
18
|
+
/** Maximum number of texts per translate request (DeepL API limit). */
|
|
19
|
+
const MAX_TEXTS_PER_REQUEST = 50;
|
|
20
|
+
/**
|
|
21
|
+
* Detects whether a DeepL API key is a free-tier key.
|
|
22
|
+
*
|
|
23
|
+
* @param apiKey - The DeepL API key.
|
|
24
|
+
* @returns True if the key is a free-tier key (ends with ':fx').
|
|
25
|
+
*/
|
|
26
|
+
function isFreeKey(apiKey) {
|
|
27
|
+
return apiKey.endsWith(':fx');
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* DeepL translation provider that implements the `AITranslationProvider` interface
|
|
31
|
+
* using the DeepL REST API v2.
|
|
32
|
+
*/
|
|
33
|
+
class DeeplTranslationProvider {
|
|
34
|
+
name = 'deepl';
|
|
35
|
+
apiKey;
|
|
36
|
+
baseUrl;
|
|
37
|
+
defaultFormality;
|
|
38
|
+
defaultModelType;
|
|
39
|
+
/**
|
|
40
|
+
* Creates a new DeepL translation provider.
|
|
41
|
+
*
|
|
42
|
+
* @param config - Provider configuration. API key defaults to DEEPL_API_KEY env var.
|
|
43
|
+
*/
|
|
44
|
+
constructor(config = {}) {
|
|
45
|
+
this.apiKey = config.apiKey ?? process.env.DEEPL_API_KEY ?? '';
|
|
46
|
+
this.defaultFormality = config.defaultFormality ?? 'default';
|
|
47
|
+
this.defaultModelType = config.defaultModelType ?? 'latency_optimized';
|
|
48
|
+
// Option wins over env, env wins over the free-vs-pro default. The explicit
|
|
49
|
+
// override (config or DEEPL_BASE_URL) must short-circuit the key-shape branch
|
|
50
|
+
// so a credential broker can point at a gateway regardless of key type.
|
|
51
|
+
if (config.baseUrl) {
|
|
52
|
+
this.baseUrl = config.baseUrl;
|
|
53
|
+
}
|
|
54
|
+
else if (process.env.DEEPL_BASE_URL) {
|
|
55
|
+
this.baseUrl = process.env.DEEPL_BASE_URL;
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
this.baseUrl = isFreeKey(this.apiKey) ? 'https://api-free.deepl.com' : 'https://api.deepl.com';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Translate one or more texts to a target language via the DeepL API.
|
|
63
|
+
*
|
|
64
|
+
* Automatically splits large input arrays into batches of 50 (the DeepL limit).
|
|
65
|
+
*
|
|
66
|
+
* @param params - Translation parameters including text(s) and target language.
|
|
67
|
+
* @returns Translation results with detected source languages.
|
|
68
|
+
*/
|
|
69
|
+
async translate(params) {
|
|
70
|
+
const texts = Array.isArray(params.text) ? params.text : [params.text];
|
|
71
|
+
if (texts.length === 0) {
|
|
72
|
+
return { translations: [] };
|
|
73
|
+
}
|
|
74
|
+
if (texts.length > MAX_TEXTS_PER_REQUEST) {
|
|
75
|
+
return this.translateBatched(texts, params);
|
|
76
|
+
}
|
|
77
|
+
return this.callTranslate(texts, params);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Get the list of languages supported by DeepL.
|
|
81
|
+
*
|
|
82
|
+
* @param type - Whether to list 'source' or 'target' languages. Defaults to 'source'.
|
|
83
|
+
* @returns Array of supported languages with formality support metadata.
|
|
84
|
+
*/
|
|
85
|
+
async getSupportedLanguages(type) {
|
|
86
|
+
const url = new URL('/v2/languages', this.baseUrl);
|
|
87
|
+
if (type) {
|
|
88
|
+
url.searchParams.set('type', type);
|
|
89
|
+
}
|
|
90
|
+
const response = await this.fetchWithRetry(url.toString(), {
|
|
91
|
+
method: 'GET',
|
|
92
|
+
headers: this.buildHeaders(),
|
|
93
|
+
});
|
|
94
|
+
if (!response.ok) {
|
|
95
|
+
throw await this.buildError('languages', response);
|
|
96
|
+
}
|
|
97
|
+
const data = (await response.json());
|
|
98
|
+
return data.map((lang) => ({
|
|
99
|
+
language: lang.language,
|
|
100
|
+
name: lang.name,
|
|
101
|
+
supportsFormality: lang.supports_formality,
|
|
102
|
+
}));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Get current API usage statistics from DeepL.
|
|
106
|
+
*
|
|
107
|
+
* @returns Character count and limit for the current billing period.
|
|
108
|
+
*/
|
|
109
|
+
async getUsage() {
|
|
110
|
+
const response = await this.fetchWithRetry(`${this.baseUrl}/v2/usage`, {
|
|
111
|
+
method: 'GET',
|
|
112
|
+
headers: this.buildHeaders(),
|
|
113
|
+
});
|
|
114
|
+
if (!response.ok) {
|
|
115
|
+
throw await this.buildError('usage', response);
|
|
116
|
+
}
|
|
117
|
+
const data = (await response.json());
|
|
118
|
+
return {
|
|
119
|
+
characterCount: data.character_count,
|
|
120
|
+
characterLimit: data.character_limit,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Handles text arrays exceeding 50 items by splitting into batches.
|
|
125
|
+
*
|
|
126
|
+
* @param texts - All input texts.
|
|
127
|
+
* @param params - Original translate params (minus text, which is replaced per batch).
|
|
128
|
+
* @returns Aggregated translation result.
|
|
129
|
+
*/
|
|
130
|
+
async translateBatched(texts, params) {
|
|
131
|
+
const allTranslations = [];
|
|
132
|
+
for (let i = 0; i < texts.length; i += MAX_TEXTS_PER_REQUEST) {
|
|
133
|
+
const batch = texts.slice(i, i + MAX_TEXTS_PER_REQUEST);
|
|
134
|
+
const result = await this.callTranslate(batch, params);
|
|
135
|
+
allTranslations.push(...result.translations);
|
|
136
|
+
}
|
|
137
|
+
return { translations: allTranslations };
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Makes a single call to the DeepL /v2/translate endpoint.
|
|
141
|
+
*
|
|
142
|
+
* @param texts - Array of texts to translate (max 50).
|
|
143
|
+
* @param params - Translation parameters.
|
|
144
|
+
* @returns Parsed translation result.
|
|
145
|
+
*/
|
|
146
|
+
async callTranslate(texts, params) {
|
|
147
|
+
const body = {
|
|
148
|
+
text: texts,
|
|
149
|
+
target_lang: params.targetLang,
|
|
150
|
+
};
|
|
151
|
+
if (params.sourceLang) {
|
|
152
|
+
body.source_lang = params.sourceLang;
|
|
153
|
+
}
|
|
154
|
+
const formality = params.formality ?? this.defaultFormality;
|
|
155
|
+
if (formality !== 'default') {
|
|
156
|
+
body.formality = formality;
|
|
157
|
+
}
|
|
158
|
+
const modelType = params.modelType ?? this.defaultModelType;
|
|
159
|
+
if (modelType !== 'latency_optimized') {
|
|
160
|
+
body.model_type = modelType;
|
|
161
|
+
}
|
|
162
|
+
if (params.preserveFormatting !== undefined) {
|
|
163
|
+
body.preserve_formatting = params.preserveFormatting;
|
|
164
|
+
}
|
|
165
|
+
if (params.glossaryId) {
|
|
166
|
+
body.glossary_id = params.glossaryId;
|
|
167
|
+
}
|
|
168
|
+
if (params.tagHandling) {
|
|
169
|
+
body.tag_handling = params.tagHandling;
|
|
170
|
+
}
|
|
171
|
+
if (params.context) {
|
|
172
|
+
body.context = params.context;
|
|
173
|
+
}
|
|
174
|
+
const response = await this.fetchWithRetry(`${this.baseUrl}/v2/translate`, {
|
|
175
|
+
method: 'POST',
|
|
176
|
+
headers: {
|
|
177
|
+
...this.buildHeaders(),
|
|
178
|
+
'Content-Type': 'application/json',
|
|
179
|
+
},
|
|
180
|
+
body: JSON.stringify(body),
|
|
181
|
+
});
|
|
182
|
+
if (!response.ok) {
|
|
183
|
+
throw await this.buildError('translate', response);
|
|
184
|
+
}
|
|
185
|
+
const data = (await response.json());
|
|
186
|
+
return {
|
|
187
|
+
translations: data.translations.map((t) => ({
|
|
188
|
+
text: t.text,
|
|
189
|
+
detectedSourceLang: t.detected_source_language,
|
|
190
|
+
})),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Builds the authorization headers for DeepL API requests.
|
|
195
|
+
*
|
|
196
|
+
* @returns Headers object with the DeepL auth key.
|
|
197
|
+
*/
|
|
198
|
+
buildHeaders() {
|
|
199
|
+
return {
|
|
200
|
+
Authorization: `DeepL-Auth-Key ${this.apiKey}`,
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Executes a fetch request with retry logic for rate-limit and server errors.
|
|
205
|
+
*
|
|
206
|
+
* Uses exponential backoff with jitter, respecting the Retry-After header when present.
|
|
207
|
+
*
|
|
208
|
+
* @param url - The URL to fetch.
|
|
209
|
+
* @param init - Fetch request options.
|
|
210
|
+
* @returns The final fetch response.
|
|
211
|
+
*/
|
|
212
|
+
async fetchWithRetry(url, init) {
|
|
213
|
+
let response = null;
|
|
214
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
215
|
+
response = await fetch(url, init);
|
|
216
|
+
if (RETRYABLE_STATUS_CODES.has(response.status) && attempt < MAX_RETRIES) {
|
|
217
|
+
const retryAfter = response.headers.get('retry-after');
|
|
218
|
+
const delayMs = retryAfter
|
|
219
|
+
? Math.min(parseInt(retryAfter, 10) * 1000, 60_000)
|
|
220
|
+
: Math.min(1000 * 2 ** attempt, 30_000);
|
|
221
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
return response;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Builds a descriptive error from a failed DeepL API response.
|
|
230
|
+
*
|
|
231
|
+
* @param endpoint - The endpoint name (for the error message).
|
|
232
|
+
* @param response - The failed fetch response.
|
|
233
|
+
* @returns An Error with a descriptive message.
|
|
234
|
+
*/
|
|
235
|
+
async buildError(endpoint, response) {
|
|
236
|
+
const errorBody = await response.text();
|
|
237
|
+
let detail = `HTTP ${response.status}`;
|
|
238
|
+
try {
|
|
239
|
+
const parsed = JSON.parse(errorBody);
|
|
240
|
+
if (parsed.message)
|
|
241
|
+
detail = parsed.message;
|
|
242
|
+
}
|
|
243
|
+
catch (_error) {
|
|
244
|
+
// JSON.parse failed — error body is not JSON; fall back to raw text if short enough.
|
|
245
|
+
if (errorBody.length > 0 && errorBody.length < 200)
|
|
246
|
+
detail = errorBody;
|
|
247
|
+
}
|
|
248
|
+
return new Error(`DeepL ${endpoint} API error: ${detail}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Creates a DeepL translation provider instance.
|
|
253
|
+
*
|
|
254
|
+
* @param config - DeepL-specific configuration (API key, base URL, defaults).
|
|
255
|
+
* @returns An `AITranslationProvider` backed by the DeepL REST API.
|
|
256
|
+
*/
|
|
257
|
+
export function createProvider(config) {
|
|
258
|
+
return new DeeplTranslationProvider(config);
|
|
259
|
+
}
|
|
260
|
+
/** Lazily-initialized provider singleton. Defers creation until first use so that env vars / secrets are resolved. */
|
|
261
|
+
let _provider = null;
|
|
262
|
+
/**
|
|
263
|
+
* The provider implementation.
|
|
264
|
+
*/
|
|
265
|
+
export const provider = new Proxy({}, {
|
|
266
|
+
get(_, prop, receiver) {
|
|
267
|
+
if (!_provider)
|
|
268
|
+
_provider = createProvider();
|
|
269
|
+
return Reflect.get(_provider, prop, receiver);
|
|
270
|
+
},
|
|
271
|
+
// set trap: methods run with `this` bound to the proxy — without it, instance-state writes land on the dummy target and are lost (see api-push-notifications-web-push)
|
|
272
|
+
set(_, prop, value) {
|
|
273
|
+
if (!_provider)
|
|
274
|
+
_provider = createProvider();
|
|
275
|
+
return Reflect.set(_provider, prop, value);
|
|
276
|
+
},
|
|
277
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL secret definitions — self-registered at import time so the
|
|
3
|
+
* runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
|
|
4
|
+
* configuration reports and actionable "not configured" errors.
|
|
5
|
+
*
|
|
6
|
+
* Content is derived MECHANICALLY from this package's mlcl registry secrets
|
|
7
|
+
* entry (label/instructions/setupUrl/example) via the fleet formula, so
|
|
8
|
+
* packages sharing a key register byte-identical definitions and
|
|
9
|
+
* registration order never matters.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import type { SecretDefinition } from '@molecule/api-secrets';
|
|
14
|
+
/** Secret definitions required by the DeepL translation bond. */
|
|
15
|
+
export declare const aiTranslationDeeplSecretDefinitions: SecretDefinition[];
|
|
16
|
+
//# sourceMappingURL=secrets.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"secrets.d.ts","sourceRoot":"","sources":["../src/secrets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AAG7D,iEAAiE;AACjE,eAAO,MAAM,mCAAmC,EAAE,gBAAgB,EASjE,CAAA"}
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL secret definitions — self-registered at import time so the
|
|
3
|
+
* runtime secrets registry (`@molecule/api-secrets`) can drive boot-time
|
|
4
|
+
* configuration reports and actionable "not configured" errors.
|
|
5
|
+
*
|
|
6
|
+
* Content is derived MECHANICALLY from this package's mlcl registry secrets
|
|
7
|
+
* entry (label/instructions/setupUrl/example) via the fleet formula, so
|
|
8
|
+
* packages sharing a key register byte-identical definitions and
|
|
9
|
+
* registration order never matters.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { registerSecrets } from '@molecule/api-secrets';
|
|
14
|
+
/** Secret definitions required by the DeepL translation bond. */
|
|
15
|
+
export const aiTranslationDeeplSecretDefinitions = [
|
|
16
|
+
{
|
|
17
|
+
key: 'DEEPL_API_KEY',
|
|
18
|
+
description: 'DeepL API key — Copy the authentication key from your DeepL account (free keys end with ":fx").',
|
|
19
|
+
helpUrl: 'https://www.deepl.com/en/your-account/keys',
|
|
20
|
+
required: true,
|
|
21
|
+
example: '279a2e9d-...:fx',
|
|
22
|
+
},
|
|
23
|
+
];
|
|
24
|
+
registerSecrets(aiTranslationDeeplSecretDefinitions);
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DeepL translation provider configuration.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for the DeepL translation provider.
|
|
8
|
+
*/
|
|
9
|
+
export interface DeeplConfig {
|
|
10
|
+
/** DeepL API key. Defaults to DEEPL_API_KEY env var. */
|
|
11
|
+
apiKey?: string;
|
|
12
|
+
/**
|
|
13
|
+
* Base URL for the DeepL API.
|
|
14
|
+
* Defaults to 'https://api-free.deepl.com' for free keys (ending in ':fx'),
|
|
15
|
+
* or 'https://api.deepl.com' for pro keys.
|
|
16
|
+
*/
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
/** Default formality preference. Defaults to 'default'. */
|
|
19
|
+
defaultFormality?: 'default' | 'more' | 'less' | 'prefer_more' | 'prefer_less';
|
|
20
|
+
/** Default model type preference. Defaults to 'latency_optimized'. */
|
|
21
|
+
defaultModelType?: 'quality_optimized' | 'prefer_quality_optimized' | 'latency_optimized';
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,wDAAwD;IACxD,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,2DAA2D;IAC3D,gBAAgB,CAAC,EAAE,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,aAAa,GAAG,aAAa,CAAA;IAC9E,sEAAsE;IACtE,gBAAgB,CAAC,EAAE,mBAAmB,GAAG,0BAA0B,GAAG,mBAAmB,CAAA;CAC1F"}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@molecule/api-ai-translation-deepl",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "DeepL translation provider for molecule.dev — text translation via DeepL API",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsc",
|
|
10
|
+
"test": "vitest run",
|
|
11
|
+
"test:watch": "vitest"
|
|
12
|
+
},
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"import": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"keywords": [
|
|
23
|
+
"molecule",
|
|
24
|
+
"ai",
|
|
25
|
+
"translation",
|
|
26
|
+
"deepl"
|
|
27
|
+
],
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"@molecule/api-ai-translation": ">=1.0.0",
|
|
31
|
+
"@molecule/api-secrets": "^1.0.0"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@molecule/api-ai-translation": "1.0.0",
|
|
35
|
+
"@types/node": "26.1.2",
|
|
36
|
+
"typescript": "6.0.3",
|
|
37
|
+
"vitest": "4.1.10"
|
|
38
|
+
}
|
|
39
|
+
}
|