@form-engine-ts/translator-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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nitta-a
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # @form-engine-ts/translator-deepl
2
+
3
+ Server-side DeepL Free/Pro asynchronous translation adapter for form-engine-ts.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @form-engine-ts/core @form-engine-ts/translator-deepl
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ```ts
14
+ import { createDeeplTranslator } from "@form-engine-ts/translator-deepl";
15
+
16
+ const translator = createDeeplTranslator({
17
+ apiKey: process.env.DEEPL_API_KEY!,
18
+ apiType: "pro"
19
+ });
20
+
21
+ const japanese = await translator.translateText("Thank you", "JA", "EN");
22
+ ```
23
+
24
+ Keep credentials on a trusted server. Use `apiType: "free"` for DeepL API Free.
package/dist/index.cjs ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createDeeplTranslator: () => createDeeplTranslator
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+ var DEEPL_ENDPOINTS = {
27
+ free: "https://api-free.deepl.com/v2/translate",
28
+ pro: "https://api.deepl.com/v2/translate"
29
+ };
30
+ function isRecord(value) {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+ function requireNonEmpty(value, name) {
34
+ if (typeof value !== "string" || value.trim().length === 0) {
35
+ throw new TypeError(`${name} must be a non-empty string.`);
36
+ }
37
+ return value.trim();
38
+ }
39
+ function redact(value, apiKey) {
40
+ return value.replaceAll(apiKey, "[redacted]");
41
+ }
42
+ function errorMessage(body, apiKey) {
43
+ if (body.length === 0) return void 0;
44
+ try {
45
+ const parsed = JSON.parse(body);
46
+ if (isRecord(parsed) && typeof parsed.message === "string") return redact(parsed.message, apiKey);
47
+ } catch {
48
+ return redact(body, apiKey);
49
+ }
50
+ return void 0;
51
+ }
52
+ function createDeeplTranslator(options) {
53
+ const apiKey = requireNonEmpty(options.apiKey, "apiKey");
54
+ const apiType = options.apiType ?? "free";
55
+ if (apiType !== "free" && apiType !== "pro") throw new TypeError('apiType must be either "free" or "pro".');
56
+ const fetchImpl = options.fetchFn ?? globalThis.fetch;
57
+ if (typeof fetchImpl !== "function") {
58
+ throw new Error("Fetch is unavailable. Pass fetchFn when creating the DeepL translator.");
59
+ }
60
+ const endpoint = DEEPL_ENDPOINTS[apiType];
61
+ const translateBatch = async (texts, targetLocale, sourceLocale) => {
62
+ if (!Array.isArray(texts) || texts.some((text) => typeof text !== "string")) {
63
+ throw new TypeError("texts must be an array of strings.");
64
+ }
65
+ const targetLang = requireNonEmpty(targetLocale, "targetLocale");
66
+ const sourceLang = sourceLocale === void 0 ? void 0 : requireNonEmpty(sourceLocale, "sourceLocale");
67
+ if (texts.length === 0) return [];
68
+ let response;
69
+ try {
70
+ response = await fetchImpl(endpoint, {
71
+ method: "POST",
72
+ headers: {
73
+ Authorization: `DeepL-Auth-Key ${apiKey}`,
74
+ "Content-Type": "application/json"
75
+ },
76
+ body: JSON.stringify({
77
+ text: texts,
78
+ target_lang: targetLang,
79
+ ...sourceLang === void 0 ? {} : { source_lang: sourceLang }
80
+ })
81
+ });
82
+ } catch (cause) {
83
+ throw new Error("DeepL request failed before receiving an HTTP response.", { cause });
84
+ }
85
+ let body;
86
+ try {
87
+ body = await response.text();
88
+ } catch (cause) {
89
+ throw new Error(`DeepL response body could not be read (HTTP ${response.status}).`, { cause });
90
+ }
91
+ if (!response.ok) {
92
+ const detail = errorMessage(body, apiKey);
93
+ throw new Error(`DeepL request failed with HTTP ${response.status}${detail === void 0 ? "." : `: ${detail}`}`);
94
+ }
95
+ let parsed;
96
+ try {
97
+ parsed = JSON.parse(body);
98
+ } catch (cause) {
99
+ throw new Error(`DeepL returned invalid JSON (HTTP ${response.status}).`, { cause });
100
+ }
101
+ if (!isRecord(parsed) || !Array.isArray(parsed.translations)) {
102
+ throw new Error("DeepL response is missing the translations array.");
103
+ }
104
+ if (parsed.translations.length !== texts.length) {
105
+ throw new Error(`DeepL returned ${parsed.translations.length} translations for ${texts.length} texts.`);
106
+ }
107
+ return parsed.translations.map((translation, index) => {
108
+ if (!isRecord(translation) || typeof translation.text !== "string") {
109
+ throw new Error(`DeepL translation at index ${index} is invalid.`);
110
+ }
111
+ return translation.text;
112
+ });
113
+ };
114
+ return {
115
+ async translateText(text, targetLocale, sourceLocale) {
116
+ if (typeof text !== "string") throw new TypeError("text must be a string.");
117
+ const translations = await translateBatch([text], targetLocale, sourceLocale);
118
+ const translated = translations[0];
119
+ if (translated === void 0) throw new Error("DeepL returned no translation.");
120
+ return translated;
121
+ },
122
+ translateBatch
123
+ };
124
+ }
125
+ // Annotate the CommonJS export names for ESM import in node:
126
+ 0 && (module.exports = {
127
+ createDeeplTranslator
128
+ });
@@ -0,0 +1,10 @@
1
+ import { AsyncTranslationAdapter } from '@form-engine-ts/core';
2
+
3
+ interface DeeplTranslatorOptions {
4
+ readonly apiKey: string;
5
+ readonly apiType?: "free" | "pro";
6
+ readonly fetchFn?: typeof fetch;
7
+ }
8
+ declare function createDeeplTranslator(options: DeeplTranslatorOptions): AsyncTranslationAdapter;
9
+
10
+ export { type DeeplTranslatorOptions, createDeeplTranslator };
@@ -0,0 +1,10 @@
1
+ import { AsyncTranslationAdapter } from '@form-engine-ts/core';
2
+
3
+ interface DeeplTranslatorOptions {
4
+ readonly apiKey: string;
5
+ readonly apiType?: "free" | "pro";
6
+ readonly fetchFn?: typeof fetch;
7
+ }
8
+ declare function createDeeplTranslator(options: DeeplTranslatorOptions): AsyncTranslationAdapter;
9
+
10
+ export { type DeeplTranslatorOptions, createDeeplTranslator };
package/dist/index.js ADDED
@@ -0,0 +1,103 @@
1
+ // src/index.ts
2
+ var DEEPL_ENDPOINTS = {
3
+ free: "https://api-free.deepl.com/v2/translate",
4
+ pro: "https://api.deepl.com/v2/translate"
5
+ };
6
+ function isRecord(value) {
7
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8
+ }
9
+ function requireNonEmpty(value, name) {
10
+ if (typeof value !== "string" || value.trim().length === 0) {
11
+ throw new TypeError(`${name} must be a non-empty string.`);
12
+ }
13
+ return value.trim();
14
+ }
15
+ function redact(value, apiKey) {
16
+ return value.replaceAll(apiKey, "[redacted]");
17
+ }
18
+ function errorMessage(body, apiKey) {
19
+ if (body.length === 0) return void 0;
20
+ try {
21
+ const parsed = JSON.parse(body);
22
+ if (isRecord(parsed) && typeof parsed.message === "string") return redact(parsed.message, apiKey);
23
+ } catch {
24
+ return redact(body, apiKey);
25
+ }
26
+ return void 0;
27
+ }
28
+ function createDeeplTranslator(options) {
29
+ const apiKey = requireNonEmpty(options.apiKey, "apiKey");
30
+ const apiType = options.apiType ?? "free";
31
+ if (apiType !== "free" && apiType !== "pro") throw new TypeError('apiType must be either "free" or "pro".');
32
+ const fetchImpl = options.fetchFn ?? globalThis.fetch;
33
+ if (typeof fetchImpl !== "function") {
34
+ throw new Error("Fetch is unavailable. Pass fetchFn when creating the DeepL translator.");
35
+ }
36
+ const endpoint = DEEPL_ENDPOINTS[apiType];
37
+ const translateBatch = async (texts, targetLocale, sourceLocale) => {
38
+ if (!Array.isArray(texts) || texts.some((text) => typeof text !== "string")) {
39
+ throw new TypeError("texts must be an array of strings.");
40
+ }
41
+ const targetLang = requireNonEmpty(targetLocale, "targetLocale");
42
+ const sourceLang = sourceLocale === void 0 ? void 0 : requireNonEmpty(sourceLocale, "sourceLocale");
43
+ if (texts.length === 0) return [];
44
+ let response;
45
+ try {
46
+ response = await fetchImpl(endpoint, {
47
+ method: "POST",
48
+ headers: {
49
+ Authorization: `DeepL-Auth-Key ${apiKey}`,
50
+ "Content-Type": "application/json"
51
+ },
52
+ body: JSON.stringify({
53
+ text: texts,
54
+ target_lang: targetLang,
55
+ ...sourceLang === void 0 ? {} : { source_lang: sourceLang }
56
+ })
57
+ });
58
+ } catch (cause) {
59
+ throw new Error("DeepL request failed before receiving an HTTP response.", { cause });
60
+ }
61
+ let body;
62
+ try {
63
+ body = await response.text();
64
+ } catch (cause) {
65
+ throw new Error(`DeepL response body could not be read (HTTP ${response.status}).`, { cause });
66
+ }
67
+ if (!response.ok) {
68
+ const detail = errorMessage(body, apiKey);
69
+ throw new Error(`DeepL request failed with HTTP ${response.status}${detail === void 0 ? "." : `: ${detail}`}`);
70
+ }
71
+ let parsed;
72
+ try {
73
+ parsed = JSON.parse(body);
74
+ } catch (cause) {
75
+ throw new Error(`DeepL returned invalid JSON (HTTP ${response.status}).`, { cause });
76
+ }
77
+ if (!isRecord(parsed) || !Array.isArray(parsed.translations)) {
78
+ throw new Error("DeepL response is missing the translations array.");
79
+ }
80
+ if (parsed.translations.length !== texts.length) {
81
+ throw new Error(`DeepL returned ${parsed.translations.length} translations for ${texts.length} texts.`);
82
+ }
83
+ return parsed.translations.map((translation, index) => {
84
+ if (!isRecord(translation) || typeof translation.text !== "string") {
85
+ throw new Error(`DeepL translation at index ${index} is invalid.`);
86
+ }
87
+ return translation.text;
88
+ });
89
+ };
90
+ return {
91
+ async translateText(text, targetLocale, sourceLocale) {
92
+ if (typeof text !== "string") throw new TypeError("text must be a string.");
93
+ const translations = await translateBatch([text], targetLocale, sourceLocale);
94
+ const translated = translations[0];
95
+ if (translated === void 0) throw new Error("DeepL returned no translation.");
96
+ return translated;
97
+ },
98
+ translateBatch
99
+ };
100
+ }
101
+ export {
102
+ createDeeplTranslator
103
+ };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@form-engine-ts/translator-deepl",
3
+ "version": "1.0.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "files": [
10
+ "dist",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "main": "./dist/index.cjs",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "require": "./dist/index.cjs"
22
+ }
23
+ },
24
+ "license": "MIT",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/nitta-a/form-engine-ts.git",
28
+ "directory": "packages/translator-deepl"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/nitta-a/form-engine-ts/issues"
32
+ },
33
+ "homepage": "https://github.com/nitta-a/form-engine-ts#readme",
34
+ "keywords": [
35
+ "form",
36
+ "translation",
37
+ "deepl",
38
+ "translator",
39
+ "typescript"
40
+ ],
41
+ "dependencies": {
42
+ "@form-engine-ts/core": "1.0.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean --external @form-engine-ts/core",
46
+ "check": "biome check . && tsc --noEmit",
47
+ "test": "vitest run --globals",
48
+ "typecheck": "tsc --noEmit"
49
+ }
50
+ }