@happyvertical/translator 0.80.0 → 0.80.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.
- package/dist/chunks/deepl-C9iR9zJ1.js +164 -0
- package/dist/chunks/deepl-C9iR9zJ1.js.map +1 -0
- package/dist/chunks/google-jZMDn2Ru.js +180 -0
- package/dist/chunks/google-jZMDn2Ru.js.map +1 -0
- package/dist/chunks/libretranslate-oJr-l5MM.js +146 -0
- package/dist/chunks/libretranslate-oJr-l5MM.js.map +1 -0
- package/dist/cli/claude-context.js +17 -17
- package/dist/cli/claude-context.js.map +1 -1
- package/dist/index.js +319 -238
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
- package/dist/chunks/deepl-CWEP0MSh.js +0 -216
- package/dist/chunks/deepl-CWEP0MSh.js.map +0 -1
- package/dist/chunks/google-KGGP9X0w.js +0 -215
- package/dist/chunks/google-KGGP9X0w.js.map +0 -1
- package/dist/chunks/libretranslate-BeC38-0r.js +0 -211
- package/dist/chunks/libretranslate-BeC38-0r.js.map +0 -1
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { AuthenticationError, InvalidTextError, QuotaExceededError, TranslationError, UnsupportedLanguageError, isValidText } from "../index.js";
|
|
2
|
+
import { getCache } from "@happyvertical/cache";
|
|
3
|
+
import * as deepl from "deepl-node";
|
|
4
|
+
//#region src/providers/deepl.ts
|
|
5
|
+
/**
|
|
6
|
+
* DeepL provider implementation with in-memory caching
|
|
7
|
+
*/
|
|
8
|
+
var DeepLProvider = class {
|
|
9
|
+
client;
|
|
10
|
+
timeout;
|
|
11
|
+
cache = null;
|
|
12
|
+
constructor(options) {
|
|
13
|
+
this.client = new deepl.Translator(options.apiKey, { serverUrl: options.freeApi ? "https://api-free.deepl.com" : void 0 });
|
|
14
|
+
this.timeout = options.timeout || 3e4;
|
|
15
|
+
this.initCache();
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Initializes the memory cache for translation results
|
|
19
|
+
*/
|
|
20
|
+
async initCache() {
|
|
21
|
+
try {
|
|
22
|
+
this.cache = await getCache({
|
|
23
|
+
provider: "memory",
|
|
24
|
+
namespace: "translator:deepl",
|
|
25
|
+
defaultTTL: 3600,
|
|
26
|
+
maxSize: 10 * 1024 * 1024,
|
|
27
|
+
maxEntries: 1e3,
|
|
28
|
+
evictionPolicy: "lru"
|
|
29
|
+
});
|
|
30
|
+
} catch (error) {
|
|
31
|
+
console.warn("Failed to initialize translation cache:", error);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Generates a cache key for translation requests
|
|
36
|
+
*/
|
|
37
|
+
getCacheKey(type, ...parts) {
|
|
38
|
+
return `${type}:${parts.join(":")}`;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Translates text from source language to target language
|
|
42
|
+
*/
|
|
43
|
+
async translate(text, targetLanguage, sourceLanguage) {
|
|
44
|
+
if (!isValidText(text)) throw new InvalidTextError("Text cannot be empty", "deepl");
|
|
45
|
+
const cacheKey = this.getCacheKey("translate", text, sourceLanguage || "auto", targetLanguage);
|
|
46
|
+
if (this.cache) {
|
|
47
|
+
const cached = await this.cache.get(cacheKey);
|
|
48
|
+
if (cached) return cached;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
const result = await this.client.translateText(text, sourceLanguage || null, targetLanguage);
|
|
52
|
+
const translationResult = {
|
|
53
|
+
translatedText: result.text,
|
|
54
|
+
sourceText: text,
|
|
55
|
+
sourceLanguage: result.detectedSourceLang.toLowerCase(),
|
|
56
|
+
targetLanguage: targetLanguage.toLowerCase(),
|
|
57
|
+
detectedSourceLanguage: !sourceLanguage,
|
|
58
|
+
raw: result
|
|
59
|
+
};
|
|
60
|
+
if (this.cache) await this.cache.set(cacheKey, translationResult);
|
|
61
|
+
return translationResult;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
throw this.mapError(error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Detects the language of the provided text
|
|
68
|
+
* Note: DeepL doesn't have a dedicated language detection API,
|
|
69
|
+
* so we translate to English and use the detected source language
|
|
70
|
+
*/
|
|
71
|
+
async detectLanguage(text) {
|
|
72
|
+
if (!isValidText(text)) throw new InvalidTextError("Text cannot be empty", "deepl");
|
|
73
|
+
const cacheKey = this.getCacheKey("detect", text);
|
|
74
|
+
if (this.cache) {
|
|
75
|
+
const cached = await this.cache.get(cacheKey);
|
|
76
|
+
if (cached) return cached;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
const result = await this.client.translateText(text, null, "en-US");
|
|
80
|
+
const detectionResult = {
|
|
81
|
+
language: result.detectedSourceLang.toLowerCase(),
|
|
82
|
+
confidence: 1,
|
|
83
|
+
raw: result
|
|
84
|
+
};
|
|
85
|
+
if (this.cache) await this.cache.set(cacheKey, detectionResult);
|
|
86
|
+
return detectionResult;
|
|
87
|
+
} catch (error) {
|
|
88
|
+
throw this.mapError(error);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Gets the list of languages supported by this provider
|
|
93
|
+
*/
|
|
94
|
+
async getSupportedLanguages() {
|
|
95
|
+
const cacheKey = this.getCacheKey("languages");
|
|
96
|
+
if (this.cache) {
|
|
97
|
+
const cached = await this.cache.get(cacheKey);
|
|
98
|
+
if (cached) return cached;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const [sourceLanguages, targetLanguages] = await Promise.all([this.client.getSourceLanguages(), this.client.getTargetLanguages()]);
|
|
102
|
+
const languageMap = /* @__PURE__ */ new Map();
|
|
103
|
+
for (const lang of sourceLanguages) languageMap.set(lang.code.toLowerCase(), {
|
|
104
|
+
code: lang.code.toLowerCase(),
|
|
105
|
+
name: lang.name
|
|
106
|
+
});
|
|
107
|
+
for (const lang of targetLanguages) {
|
|
108
|
+
const code = lang.code.toLowerCase();
|
|
109
|
+
if (!languageMap.has(code)) languageMap.set(code, {
|
|
110
|
+
code,
|
|
111
|
+
name: lang.name
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
const result = Array.from(languageMap.values());
|
|
115
|
+
if (this.cache) await this.cache.set(cacheKey, result, 86400);
|
|
116
|
+
return result;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
throw this.mapError(error);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Translates multiple texts in a single batch operation
|
|
123
|
+
*/
|
|
124
|
+
async translateBatch(texts, targetLanguage, sourceLanguage) {
|
|
125
|
+
if (texts.length === 0) return [];
|
|
126
|
+
try {
|
|
127
|
+
const results = await this.client.translateText(texts, sourceLanguage || null, targetLanguage);
|
|
128
|
+
const resultsArray = Array.isArray(results) ? results : [results];
|
|
129
|
+
return texts.map((text, index) => {
|
|
130
|
+
const result = resultsArray[index];
|
|
131
|
+
return {
|
|
132
|
+
translatedText: result.text,
|
|
133
|
+
sourceText: text,
|
|
134
|
+
sourceLanguage: result.detectedSourceLang.toLowerCase(),
|
|
135
|
+
targetLanguage: targetLanguage.toLowerCase(),
|
|
136
|
+
detectedSourceLanguage: !sourceLanguage,
|
|
137
|
+
raw: result
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
} catch (error) {
|
|
141
|
+
throw this.mapError(error);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Maps DeepL errors to standardized error types
|
|
146
|
+
*/
|
|
147
|
+
mapError(error) {
|
|
148
|
+
if (error instanceof deepl.DeepLError) {
|
|
149
|
+
if (error.message.includes("401") || error.message.includes("403")) return new AuthenticationError("deepl");
|
|
150
|
+
if (error.message.includes("429") || error.message.includes("quota")) return new QuotaExceededError("deepl");
|
|
151
|
+
if (error.message.includes("language") || error.message.includes("not supported")) {
|
|
152
|
+
const match = error.message.match(/language[:\s]+([a-z-]+)/i);
|
|
153
|
+
return new UnsupportedLanguageError(match ? match[1] : "unknown", "deepl");
|
|
154
|
+
}
|
|
155
|
+
return new TranslationError(error.message, "DEEPL_ERROR", "deepl");
|
|
156
|
+
}
|
|
157
|
+
const err = error;
|
|
158
|
+
return new TranslationError(err?.message || "Translation failed", err?.code || "UNKNOWN_ERROR", "deepl");
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
//#endregion
|
|
162
|
+
export { DeepLProvider };
|
|
163
|
+
|
|
164
|
+
//# sourceMappingURL=deepl-C9iR9zJ1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deepl-C9iR9zJ1.js","names":[],"sources":["../../src/providers/deepl.ts"],"sourcesContent":["/**\n * DeepL provider implementation\n */\n\nimport type { CacheAdapter } from '@happyvertical/cache';\nimport { getCache } from '@happyvertical/cache';\nimport * as deepl from 'deepl-node';\nimport type {\n DeepLOptions,\n LanguageDetectionResult,\n SupportedLanguage,\n TranslationProvider,\n TranslationResult,\n} from '../shared/types';\nimport {\n AuthenticationError,\n InvalidTextError,\n QuotaExceededError,\n TranslationError,\n UnsupportedLanguageError,\n} from '../shared/types';\nimport { isValidText } from '../shared/utils';\n\n/**\n * DeepL provider implementation with in-memory caching\n */\nexport class DeepLProvider implements TranslationProvider {\n private client: deepl.Translator;\n private timeout: number;\n private cache: CacheAdapter | null = null;\n\n constructor(options: DeepLOptions) {\n this.client = new deepl.Translator(options.apiKey, {\n serverUrl: options.freeApi ? 'https://api-free.deepl.com' : undefined,\n });\n this.timeout = options.timeout || 30000;\n\n // Initialize memory cache asynchronously\n this.initCache();\n }\n\n /**\n * Initializes the memory cache for translation results\n */\n private async initCache(): Promise<void> {\n try {\n this.cache = await getCache({\n provider: 'memory',\n namespace: 'translator:deepl',\n defaultTTL: 3600, // 1 hour cache\n maxSize: 10 * 1024 * 1024, // 10MB\n maxEntries: 1000,\n evictionPolicy: 'lru',\n });\n } catch (error) {\n // Cache initialization failure shouldn't break the provider\n console.warn('Failed to initialize translation cache:', error);\n }\n }\n\n /**\n * Generates a cache key for translation requests\n */\n private getCacheKey(type: string, ...parts: string[]): string {\n return `${type}:${parts.join(':')}`;\n }\n\n /**\n * Translates text from source language to target language\n */\n async translate(\n text: string,\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'deepl');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey(\n 'translate',\n text,\n sourceLanguage || 'auto',\n targetLanguage,\n );\n if (this.cache) {\n const cached = await this.cache.get<TranslationResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const result = await this.client.translateText(\n text,\n (sourceLanguage as any) || null,\n targetLanguage as any,\n );\n\n const translationResult: TranslationResult = {\n translatedText: result.text,\n sourceText: text,\n sourceLanguage: result.detectedSourceLang.toLowerCase(),\n targetLanguage: targetLanguage.toLowerCase(),\n detectedSourceLanguage: !sourceLanguage,\n raw: result,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, translationResult);\n }\n\n return translationResult;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Detects the language of the provided text\n * Note: DeepL doesn't have a dedicated language detection API,\n * so we translate to English and use the detected source language\n */\n async detectLanguage(text: string): Promise<LanguageDetectionResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'deepl');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey('detect', text);\n if (this.cache) {\n const cached = await this.cache.get<LanguageDetectionResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n // Translate to English to get source language detection\n const result = await this.client.translateText(\n text,\n null,\n 'en-US' as any,\n );\n\n const detectionResult: LanguageDetectionResult = {\n language: result.detectedSourceLang.toLowerCase(),\n confidence: 1.0, // DeepL doesn't provide confidence scores\n raw: result,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, detectionResult);\n }\n\n return detectionResult;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Gets the list of languages supported by this provider\n */\n async getSupportedLanguages(): Promise<SupportedLanguage[]> {\n // Check cache first (this data rarely changes)\n const cacheKey = this.getCacheKey('languages');\n if (this.cache) {\n const cached = await this.cache.get<SupportedLanguage[]>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [sourceLanguages, targetLanguages] = await Promise.all([\n this.client.getSourceLanguages(),\n this.client.getTargetLanguages(),\n ]);\n\n // Combine source and target languages, removing duplicates\n const languageMap = new Map<string, SupportedLanguage>();\n\n for (const lang of sourceLanguages) {\n languageMap.set(lang.code.toLowerCase(), {\n code: lang.code.toLowerCase(),\n name: lang.name,\n });\n }\n\n for (const lang of targetLanguages) {\n const code = lang.code.toLowerCase();\n if (!languageMap.has(code)) {\n languageMap.set(code, {\n code,\n name: lang.name,\n });\n }\n }\n\n const result = Array.from(languageMap.values());\n\n // Cache for longer (24 hours) as language lists rarely change\n if (this.cache) {\n await this.cache.set(cacheKey, result, 86400);\n }\n\n return result;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Translates multiple texts in a single batch operation\n */\n async translateBatch(\n texts: string[],\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult[]> {\n if (texts.length === 0) {\n return [];\n }\n\n try {\n const results = await this.client.translateText(\n texts,\n (sourceLanguage as any) || null,\n targetLanguage as any,\n );\n\n const resultsArray = Array.isArray(results) ? results : [results];\n\n return texts.map((text, index) => {\n const result = resultsArray[index];\n return {\n translatedText: result.text,\n sourceText: text,\n sourceLanguage: result.detectedSourceLang.toLowerCase(),\n targetLanguage: targetLanguage.toLowerCase(),\n detectedSourceLanguage: !sourceLanguage,\n raw: result,\n };\n });\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Maps DeepL errors to standardized error types\n */\n private mapError(error: unknown): TranslationError {\n if (error instanceof deepl.DeepLError) {\n if (error.message.includes('401') || error.message.includes('403')) {\n return new AuthenticationError('deepl');\n }\n\n if (error.message.includes('429') || error.message.includes('quota')) {\n return new QuotaExceededError('deepl');\n }\n\n if (\n error.message.includes('language') ||\n error.message.includes('not supported')\n ) {\n const match = error.message.match(/language[:\\s]+([a-z-]+)/i);\n const language = match ? match[1] : 'unknown';\n return new UnsupportedLanguageError(language, 'deepl');\n }\n\n return new TranslationError(error.message, 'DEEPL_ERROR', 'deepl');\n }\n\n const err = error as any;\n return new TranslationError(\n err?.message || 'Translation failed',\n err?.code || 'UNKNOWN_ERROR',\n 'deepl',\n );\n }\n}\n"],"mappings":";;;;;;;AA0BA,IAAa,gBAAb,MAA0D;CACxD;CACA;CACA,QAAqC;CAErC,YAAY,SAAuB;EACjC,KAAK,SAAS,IAAI,MAAM,WAAW,QAAQ,QAAQ,EACjD,WAAW,QAAQ,UAAU,+BAA+B,KAAA,EAC9D,CAAC;EACD,KAAK,UAAU,QAAQ,WAAW;EAGlC,KAAK,UAAU;CACjB;;;;CAKA,MAAc,YAA2B;EACvC,IAAI;GACF,KAAK,QAAQ,MAAM,SAAS;IAC1B,UAAU;IACV,WAAW;IACX,YAAY;IACZ,SAAS,KAAK,OAAO;IACrB,YAAY;IACZ,gBAAgB;GAClB,CAAC;EACH,SAAS,OAAO;GAEd,QAAQ,KAAK,2CAA2C,KAAK;EAC/D;CACF;;;;CAKA,YAAoB,MAAc,GAAG,OAAyB;EAC5D,OAAO,GAAG,KAAK,GAAG,MAAM,KAAK,GAAG;CAClC;;;;CAKA,MAAM,UACJ,MACA,gBACA,gBAC4B;EAC5B,IAAI,CAAC,YAAY,IAAI,GACnB,MAAM,IAAI,iBAAiB,wBAAwB,OAAO;EAI5D,MAAM,WAAW,KAAK,YACpB,aACA,MACA,kBAAkB,QAClB,cACF;EACA,IAAI,KAAK,OAAO;GACd,MAAM,SAAS,MAAM,KAAK,MAAM,IAAuB,QAAQ;GAC/D,IAAI,QACF,OAAO;EAEX;EAEA,IAAI;GACF,MAAM,SAAS,MAAM,KAAK,OAAO,cAC/B,MACC,kBAA0B,MAC3B,cACF;GAEA,MAAM,oBAAuC;IAC3C,gBAAgB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AAM,0BAA0B;IAE5D,OAAO,IAAI,yBADM,QAAQ,MAAM,KAAK,WACU,OAAO;GACvD;GAEA,OAAO,IAAI,iBAAiB,MAAM,SAAS,eAAe,OAAO;EACnE;EAEA,MAAM,MAAM;EACZ,OAAO,IAAI,iBACT,KAAK,WAAW,sBAChB,KAAK,QAAQ,iBACb,OACF;CACF;AACF"}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { AuthenticationError, InvalidTextError, QuotaExceededError, TranslationError, UnsupportedLanguageError, getLanguageName, isValidText, normalizeConfidence } from "../index.js";
|
|
2
|
+
import { getCache } from "@happyvertical/cache";
|
|
3
|
+
import { v2 } from "@google-cloud/translate";
|
|
4
|
+
//#region src/providers/google.ts
|
|
5
|
+
/**
|
|
6
|
+
* Google Translate provider implementation
|
|
7
|
+
*/
|
|
8
|
+
var { Translate } = v2;
|
|
9
|
+
/**
|
|
10
|
+
* Google Translate provider implementation with in-memory caching
|
|
11
|
+
*/
|
|
12
|
+
var GoogleTranslateProvider = class {
|
|
13
|
+
client;
|
|
14
|
+
timeout;
|
|
15
|
+
cache = null;
|
|
16
|
+
constructor(options) {
|
|
17
|
+
this.client = new Translate({
|
|
18
|
+
key: options.apiKey,
|
|
19
|
+
projectId: options.projectId
|
|
20
|
+
});
|
|
21
|
+
this.timeout = options.timeout || 3e4;
|
|
22
|
+
this.initCache();
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Initializes the memory cache for translation results
|
|
26
|
+
*/
|
|
27
|
+
async initCache() {
|
|
28
|
+
try {
|
|
29
|
+
this.cache = await getCache({
|
|
30
|
+
provider: "memory",
|
|
31
|
+
namespace: "translator:google",
|
|
32
|
+
defaultTTL: 3600,
|
|
33
|
+
maxSize: 10 * 1024 * 1024,
|
|
34
|
+
maxEntries: 1e3,
|
|
35
|
+
evictionPolicy: "lru"
|
|
36
|
+
});
|
|
37
|
+
} catch (error) {
|
|
38
|
+
console.warn("Failed to initialize translation cache:", error);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Generates a cache key for translation requests
|
|
43
|
+
*/
|
|
44
|
+
getCacheKey(type, ...parts) {
|
|
45
|
+
return `${type}:${parts.join(":")}`;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Translates text from source language to target language
|
|
49
|
+
*/
|
|
50
|
+
async translate(text, targetLanguage, sourceLanguage) {
|
|
51
|
+
if (!isValidText(text)) throw new InvalidTextError("Text cannot be empty", "google");
|
|
52
|
+
const cacheKey = this.getCacheKey("translate", text, sourceLanguage || "auto", targetLanguage);
|
|
53
|
+
if (this.cache) {
|
|
54
|
+
const cached = await this.cache.get(cacheKey);
|
|
55
|
+
if (cached) return cached;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const [translation] = await this.client.translate(text, {
|
|
59
|
+
from: sourceLanguage,
|
|
60
|
+
to: targetLanguage
|
|
61
|
+
});
|
|
62
|
+
const detectedSourceLanguage = !sourceLanguage;
|
|
63
|
+
let actualSourceLanguage = sourceLanguage;
|
|
64
|
+
if (!actualSourceLanguage) {
|
|
65
|
+
const [detection] = await this.client.detect(text);
|
|
66
|
+
actualSourceLanguage = Array.isArray(detection) ? detection[0].language : detection.language;
|
|
67
|
+
}
|
|
68
|
+
const result = {
|
|
69
|
+
translatedText: translation,
|
|
70
|
+
sourceText: text,
|
|
71
|
+
sourceLanguage: actualSourceLanguage || "unknown",
|
|
72
|
+
targetLanguage,
|
|
73
|
+
detectedSourceLanguage,
|
|
74
|
+
raw: translation
|
|
75
|
+
};
|
|
76
|
+
if (this.cache) await this.cache.set(cacheKey, result);
|
|
77
|
+
return result;
|
|
78
|
+
} catch (error) {
|
|
79
|
+
throw this.mapError(error);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Detects the language of the provided text
|
|
84
|
+
*/
|
|
85
|
+
async detectLanguage(text) {
|
|
86
|
+
if (!isValidText(text)) throw new InvalidTextError("Text cannot be empty", "google");
|
|
87
|
+
const cacheKey = this.getCacheKey("detect", text);
|
|
88
|
+
if (this.cache) {
|
|
89
|
+
const cached = await this.cache.get(cacheKey);
|
|
90
|
+
if (cached) return cached;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const [detections] = await this.client.detect(text);
|
|
94
|
+
const detectionsArray = Array.isArray(detections) ? detections : [detections];
|
|
95
|
+
if (detectionsArray.length === 0) throw new TranslationError("No language detected", "NO_DETECTION", "google");
|
|
96
|
+
const primary = detectionsArray[0];
|
|
97
|
+
const result = {
|
|
98
|
+
language: primary.language,
|
|
99
|
+
confidence: normalizeConfidence(primary.confidence || 0),
|
|
100
|
+
alternatives: detectionsArray.slice(1).map((d) => ({
|
|
101
|
+
language: d.language,
|
|
102
|
+
confidence: normalizeConfidence(d.confidence || 0)
|
|
103
|
+
})),
|
|
104
|
+
raw: detections
|
|
105
|
+
};
|
|
106
|
+
if (this.cache) await this.cache.set(cacheKey, result);
|
|
107
|
+
return result;
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (error instanceof TranslationError) throw error;
|
|
110
|
+
throw this.mapError(error);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Gets the list of languages supported by this provider
|
|
115
|
+
*/
|
|
116
|
+
async getSupportedLanguages() {
|
|
117
|
+
const cacheKey = this.getCacheKey("languages");
|
|
118
|
+
if (this.cache) {
|
|
119
|
+
const cached = await this.cache.get(cacheKey);
|
|
120
|
+
if (cached) return cached;
|
|
121
|
+
}
|
|
122
|
+
try {
|
|
123
|
+
const [languages] = await this.client.getLanguages();
|
|
124
|
+
const result = languages.map((lang) => ({
|
|
125
|
+
code: lang.code,
|
|
126
|
+
name: lang.name || getLanguageName(lang.code)
|
|
127
|
+
}));
|
|
128
|
+
if (this.cache) await this.cache.set(cacheKey, result, 86400);
|
|
129
|
+
return result;
|
|
130
|
+
} catch (error) {
|
|
131
|
+
throw this.mapError(error);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Translates multiple texts in a single batch operation
|
|
136
|
+
*/
|
|
137
|
+
async translateBatch(texts, targetLanguage, sourceLanguage) {
|
|
138
|
+
if (texts.length === 0) return [];
|
|
139
|
+
try {
|
|
140
|
+
const [translations] = await this.client.translate(texts, {
|
|
141
|
+
from: sourceLanguage,
|
|
142
|
+
to: targetLanguage
|
|
143
|
+
});
|
|
144
|
+
const translationsArray = Array.isArray(translations) ? translations : [translations];
|
|
145
|
+
const detectedSourceLanguage = !sourceLanguage;
|
|
146
|
+
let actualSourceLanguage = sourceLanguage;
|
|
147
|
+
if (!actualSourceLanguage && texts.length > 0) {
|
|
148
|
+
const [detection] = await this.client.detect(texts[0]);
|
|
149
|
+
actualSourceLanguage = Array.isArray(detection) ? detection[0].language : detection.language;
|
|
150
|
+
}
|
|
151
|
+
return texts.map((text, index) => ({
|
|
152
|
+
translatedText: translationsArray[index] || text,
|
|
153
|
+
sourceText: text,
|
|
154
|
+
sourceLanguage: actualSourceLanguage || "unknown",
|
|
155
|
+
targetLanguage,
|
|
156
|
+
detectedSourceLanguage,
|
|
157
|
+
raw: translationsArray[index]
|
|
158
|
+
}));
|
|
159
|
+
} catch (error) {
|
|
160
|
+
throw this.mapError(error);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Maps Google Translate errors to standardized error types
|
|
165
|
+
*/
|
|
166
|
+
mapError(error) {
|
|
167
|
+
const err = error;
|
|
168
|
+
if (err.code === 403 || err.code === 401) return new AuthenticationError("google");
|
|
169
|
+
if (err.code === 429) return new QuotaExceededError("google");
|
|
170
|
+
if (err.code === 400 && err.message?.includes("language")) {
|
|
171
|
+
const match = err.message.match(/language[:\s]+([a-z-]+)/i);
|
|
172
|
+
return new UnsupportedLanguageError(match ? match[1] : "unknown", "google");
|
|
173
|
+
}
|
|
174
|
+
return new TranslationError(err.message || "Translation failed", err.code || "UNKNOWN_ERROR", "google");
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
//#endregion
|
|
178
|
+
export { GoogleTranslateProvider };
|
|
179
|
+
|
|
180
|
+
//# sourceMappingURL=google-jZMDn2Ru.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"google-jZMDn2Ru.js","names":[],"sources":["../../src/providers/google.ts"],"sourcesContent":["/**\n * Google Translate provider implementation\n */\n\nimport { v2 } from '@google-cloud/translate';\nimport type { CacheAdapter } from '@happyvertical/cache';\nimport { getCache } from '@happyvertical/cache';\nimport type {\n GoogleTranslateOptions,\n LanguageDetectionResult,\n SupportedLanguage,\n TranslationProvider,\n TranslationResult,\n} from '../shared/types';\nimport {\n AuthenticationError,\n InvalidTextError,\n QuotaExceededError,\n TranslationError,\n UnsupportedLanguageError,\n} from '../shared/types';\nimport {\n getLanguageName,\n isValidText,\n normalizeConfidence,\n} from '../shared/utils';\n\nconst { Translate } = v2;\n\n/**\n * Google Translate provider implementation with in-memory caching\n */\nexport class GoogleTranslateProvider implements TranslationProvider {\n private client: InstanceType<typeof Translate>;\n private timeout: number;\n private cache: CacheAdapter | null = null;\n\n constructor(options: GoogleTranslateOptions) {\n this.client = new Translate({\n key: options.apiKey,\n projectId: options.projectId,\n });\n this.timeout = options.timeout || 30000;\n\n // Initialize memory cache asynchronously\n this.initCache();\n }\n\n /**\n * Initializes the memory cache for translation results\n */\n private async initCache(): Promise<void> {\n try {\n this.cache = await getCache({\n provider: 'memory',\n namespace: 'translator:google',\n defaultTTL: 3600, // 1 hour cache\n maxSize: 10 * 1024 * 1024, // 10MB\n maxEntries: 1000,\n evictionPolicy: 'lru',\n });\n } catch (error) {\n // Cache initialization failure shouldn't break the provider\n console.warn('Failed to initialize translation cache:', error);\n }\n }\n\n /**\n * Generates a cache key for translation requests\n */\n private getCacheKey(type: string, ...parts: string[]): string {\n return `${type}:${parts.join(':')}`;\n }\n\n /**\n * Translates text from source language to target language\n */\n async translate(\n text: string,\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'google');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey(\n 'translate',\n text,\n sourceLanguage || 'auto',\n targetLanguage,\n );\n if (this.cache) {\n const cached = await this.cache.get<TranslationResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [translation] = await this.client.translate(text, {\n from: sourceLanguage,\n to: targetLanguage,\n });\n\n // Detect if source language was auto-detected\n const detectedSourceLanguage = !sourceLanguage;\n\n // Get detected language if not provided\n let actualSourceLanguage = sourceLanguage;\n if (!actualSourceLanguage) {\n const [detection] = await this.client.detect(text);\n actualSourceLanguage = Array.isArray(detection)\n ? detection[0].language\n : detection.language;\n }\n\n const result: TranslationResult = {\n translatedText: translation,\n sourceText: text,\n sourceLanguage: actualSourceLanguage || 'unknown',\n targetLanguage,\n detectedSourceLanguage,\n raw: translation,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, result);\n }\n\n return result;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Detects the language of the provided text\n */\n async detectLanguage(text: string): Promise<LanguageDetectionResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'google');\n }\n\n // Check cache first\n const cacheKey = this.getCacheKey('detect', text);\n if (this.cache) {\n const cached = await this.cache.get<LanguageDetectionResult>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [detections] = await this.client.detect(text);\n const detectionsArray = Array.isArray(detections)\n ? detections\n : [detections];\n\n if (detectionsArray.length === 0) {\n throw new TranslationError(\n 'No language detected',\n 'NO_DETECTION',\n 'google',\n );\n }\n\n const primary = detectionsArray[0];\n\n const result: LanguageDetectionResult = {\n language: primary.language,\n confidence: normalizeConfidence(primary.confidence || 0),\n alternatives: detectionsArray.slice(1).map((d) => ({\n language: d.language,\n confidence: normalizeConfidence(d.confidence || 0),\n })),\n raw: detections,\n };\n\n // Cache the result\n if (this.cache) {\n await this.cache.set(cacheKey, result);\n }\n\n return result;\n } catch (error) {\n if (error instanceof TranslationError) {\n throw error;\n }\n throw this.mapError(error);\n }\n }\n\n /**\n * Gets the list of languages supported by this provider\n */\n async getSupportedLanguages(): Promise<SupportedLanguage[]> {\n // Check cache first (this data rarely changes)\n const cacheKey = this.getCacheKey('languages');\n if (this.cache) {\n const cached = await this.cache.get<SupportedLanguage[]>(cacheKey);\n if (cached) {\n return cached;\n }\n }\n\n try {\n const [languages] = await this.client.getLanguages();\n\n const result = languages.map((lang) => ({\n code: lang.code,\n name: lang.name || getLanguageName(lang.code),\n }));\n\n // Cache for longer (24 hours) as language lists rarely change\n if (this.cache) {\n await this.cache.set(cacheKey, result, 86400);\n }\n\n return result;\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Translates multiple texts in a single batch operation\n */\n async translateBatch(\n texts: string[],\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult[]> {\n if (texts.length === 0) {\n return [];\n }\n\n try {\n const [translations] = await this.client.translate(texts, {\n from: sourceLanguage,\n to: targetLanguage,\n });\n\n const translationsArray = Array.isArray(translations)\n ? translations\n : [translations];\n\n const detectedSourceLanguage = !sourceLanguage;\n let actualSourceLanguage = sourceLanguage;\n\n // Detect source language for first text if not provided\n if (!actualSourceLanguage && texts.length > 0) {\n const [detection] = await this.client.detect(texts[0]);\n actualSourceLanguage = Array.isArray(detection)\n ? detection[0].language\n : detection.language;\n }\n\n return texts.map((text, index) => ({\n translatedText: translationsArray[index] || text,\n sourceText: text,\n sourceLanguage: actualSourceLanguage || 'unknown',\n targetLanguage,\n detectedSourceLanguage,\n raw: translationsArray[index],\n }));\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Maps Google Translate errors to standardized error types\n */\n private mapError(error: unknown): TranslationError {\n const err = error as any;\n\n // Check for common error codes\n if (err.code === 403 || err.code === 401) {\n return new AuthenticationError('google');\n }\n\n if (err.code === 429) {\n return new QuotaExceededError('google');\n }\n\n if (err.code === 400 && err.message?.includes('language')) {\n const match = err.message.match(/language[:\\s]+([a-z-]+)/i);\n const language = match ? match[1] : 'unknown';\n return new UnsupportedLanguageError(language, 'google');\n }\n\n return new TranslationError(\n err.message || 'Translation failed',\n err.code || 'UNKNOWN_ERROR',\n 'google',\n );\n }\n}\n"],"mappings":";;;;;;;AA2BA,IAAM,EAAE,cAAc;;;;AAKtB,IAAa,0BAAb,MAAoE;CAClE;CACA;CACA,QAAqC;CAErC,YAAY,SAAiC;EAC3C,KAAK,SAAS,IAAI,UAAU;GAC1B,KAAK,QAAQ;GACb,WAAW,QAAQ;EACrB,CAAC;EACD,KAAK,UAAU,QAAQ,WAAW;EAGlC,KAAK,UAAU;CACjB;;;;CAKA,MAAc,YAA2B;EACvC,IAAI;GACF,KAAK,QAAQ,MAAM,SAAS;IAC1B,UAAU;IACV,WAAW;IACX,YAAY;IACZ,SAAS,KAAK,OAAO;IACrB,YAAY;IACZ,gBAAgB;GAClB,CAAC;EACH,SAAS,OAAO;GAEd,QAAQ,KAAK,2CAA2C,KAAK;EAC/D;CACF;;;;CAKA,YAAoB,MAAc,GAAG,OAAyB;EAC5D,OAAO,GAAG,KAAK,GAAG,MAAM,KAAK,GAAG;CAClC;;;;CAKA,MAAM,UACJ,MACA,gBACA,gBAC4B;EAC5B,IAAI,CAAC,YAAY,IAAI,GACnB,MAAM,IAAI,iBAAiB,wBAAwB,QAAQ;EAI7D,MAAM,WAAW,KAAK,YACpB,aACA,MACA,kBAAkB,QAClB,cACF;EACA,IAAI,KAAK,OAAO;GACd,MAAM,SAAS,MAAM,KAAK,MAAM,IAAuB,QAAQ;GAC/D,IAAI,QACF,OAAO;EAEX;EAEA,IAAI;GACF,MAAM,CAAC,eAAe,MAAM,KAAK,OAAO,UAAU,MAAM;IACtD,MAAM;IACN,IAAI;GACN,CAAC;GAGD,MAAM,yBAAyB,CAAC;GAGhC,IAAI,uBAAuB;GAC3B,IAAI,CAAC,sBAAsB;I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oBAAoB,QAAQ;EAGzC,IAAI,IAAI,SAAS,KACf,OAAO,IAAI,mBAAmB,QAAQ;EAGxC,IAAI,IAAI,SAAS,OAAO,IAAI,SAAS,SAAS,UAAU,GAAG;GACzD,MAAM,QAAQ,IAAI,QAAQ,MAAM,0BAA0B;GAE1D,OAAO,IAAI,yBADM,QAAQ,MAAM,KAAK,WACU,QAAQ;EACxD;EAEA,OAAO,IAAI,iBACT,IAAI,WAAW,sBACf,IAAI,QAAQ,iBACZ,QACF;CACF;AACF"}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { AuthenticationError, InvalidTextError, TranslationError, UnsupportedLanguageError, getLanguageName, isValidText } from "../index.js";
|
|
2
|
+
//#region src/providers/libretranslate.ts
|
|
3
|
+
/**
|
|
4
|
+
* LibreTranslate provider implementation
|
|
5
|
+
*/
|
|
6
|
+
var LibreTranslateProvider = class {
|
|
7
|
+
baseUrl;
|
|
8
|
+
apiKey;
|
|
9
|
+
timeout;
|
|
10
|
+
constructor(options) {
|
|
11
|
+
this.baseUrl = options.apiUrl || "https://libretranslate.com";
|
|
12
|
+
this.apiKey = options.apiKey;
|
|
13
|
+
this.timeout = options.timeout || 3e4;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Translates text from source language to target language
|
|
17
|
+
*/
|
|
18
|
+
async translate(text, targetLanguage, sourceLanguage) {
|
|
19
|
+
if (!isValidText(text)) throw new InvalidTextError("Text cannot be empty", "libretranslate");
|
|
20
|
+
try {
|
|
21
|
+
const body = {
|
|
22
|
+
q: text,
|
|
23
|
+
target: targetLanguage,
|
|
24
|
+
format: "text"
|
|
25
|
+
};
|
|
26
|
+
if (sourceLanguage) body.source = sourceLanguage;
|
|
27
|
+
else body.source = "auto";
|
|
28
|
+
if (this.apiKey) body.api_key = this.apiKey;
|
|
29
|
+
const data = await this.fetchLibreTranslate("/translate", body);
|
|
30
|
+
return {
|
|
31
|
+
translatedText: data.translatedText,
|
|
32
|
+
sourceText: text,
|
|
33
|
+
sourceLanguage: data.detectedLanguage?.language || sourceLanguage || "unknown",
|
|
34
|
+
targetLanguage,
|
|
35
|
+
confidence: data.detectedLanguage?.confidence,
|
|
36
|
+
detectedSourceLanguage: !sourceLanguage,
|
|
37
|
+
raw: data
|
|
38
|
+
};
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw this.mapError(error);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Detects the language of the provided text
|
|
45
|
+
*/
|
|
46
|
+
async detectLanguage(text) {
|
|
47
|
+
if (!isValidText(text)) throw new InvalidTextError("Text cannot be empty", "libretranslate");
|
|
48
|
+
try {
|
|
49
|
+
const body = { q: text };
|
|
50
|
+
if (this.apiKey) body.api_key = this.apiKey;
|
|
51
|
+
const response = await this.fetchLibreTranslate("/detect", body);
|
|
52
|
+
if (Array.isArray(response)) {
|
|
53
|
+
const detections = response;
|
|
54
|
+
if (detections.length === 0) throw new TranslationError("No language detected", "NO_DETECTION", "libretranslate");
|
|
55
|
+
return {
|
|
56
|
+
language: detections[0].language,
|
|
57
|
+
confidence: detections[0].confidence,
|
|
58
|
+
alternatives: detections.slice(1).map((d) => ({
|
|
59
|
+
language: d.language,
|
|
60
|
+
confidence: d.confidence
|
|
61
|
+
})),
|
|
62
|
+
raw: response
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
throw new TranslationError("Invalid detection response", "INVALID_RESPONSE", "libretranslate");
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (error instanceof TranslationError) throw error;
|
|
68
|
+
throw this.mapError(error);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Gets the list of languages supported by this provider
|
|
73
|
+
*/
|
|
74
|
+
async getSupportedLanguages() {
|
|
75
|
+
try {
|
|
76
|
+
const response = await this.fetchLibreTranslate("/languages", void 0, "GET");
|
|
77
|
+
if (Array.isArray(response)) return response.map((lang) => ({
|
|
78
|
+
code: lang.code,
|
|
79
|
+
name: lang.name || getLanguageName(lang.code)
|
|
80
|
+
}));
|
|
81
|
+
throw new TranslationError("Invalid languages response", "INVALID_RESPONSE", "libretranslate");
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error instanceof TranslationError) throw error;
|
|
84
|
+
throw this.mapError(error);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Translates multiple texts in a single batch operation
|
|
89
|
+
* Note: LibreTranslate doesn't have native batch support,
|
|
90
|
+
* so we translate texts sequentially
|
|
91
|
+
*/
|
|
92
|
+
async translateBatch(texts, targetLanguage, sourceLanguage) {
|
|
93
|
+
if (texts.length === 0) return [];
|
|
94
|
+
const results = [];
|
|
95
|
+
for (const text of texts) {
|
|
96
|
+
const result = await this.translate(text, targetLanguage, sourceLanguage);
|
|
97
|
+
results.push(result);
|
|
98
|
+
}
|
|
99
|
+
return results;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Makes an HTTP request to LibreTranslate API
|
|
103
|
+
*/
|
|
104
|
+
async fetchLibreTranslate(endpoint, body, method = "POST") {
|
|
105
|
+
const url = `${this.baseUrl}${endpoint}`;
|
|
106
|
+
const controller = new AbortController();
|
|
107
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
108
|
+
try {
|
|
109
|
+
const options = {
|
|
110
|
+
method,
|
|
111
|
+
signal: controller.signal
|
|
112
|
+
};
|
|
113
|
+
if (method === "POST" && body) {
|
|
114
|
+
options.headers = { "Content-Type": "application/json" };
|
|
115
|
+
options.body = JSON.stringify(body);
|
|
116
|
+
}
|
|
117
|
+
const response = await fetch(url, options);
|
|
118
|
+
clearTimeout(timeoutId);
|
|
119
|
+
if (!response.ok) {
|
|
120
|
+
if (response.status === 401 || response.status === 403) throw new AuthenticationError("libretranslate");
|
|
121
|
+
if (response.status === 400) {
|
|
122
|
+
if ((await response.json().catch(() => ({}))).error?.includes("language")) throw new UnsupportedLanguageError(body.source || body.target || "unknown", "libretranslate");
|
|
123
|
+
}
|
|
124
|
+
throw new TranslationError(`HTTP ${response.status}: ${response.statusText}`, "HTTP_ERROR", "libretranslate");
|
|
125
|
+
}
|
|
126
|
+
return await response.json();
|
|
127
|
+
} catch (error) {
|
|
128
|
+
clearTimeout(timeoutId);
|
|
129
|
+
if (error instanceof TranslationError) throw error;
|
|
130
|
+
if (error.name === "AbortError") throw new TranslationError("Request timeout", "TIMEOUT", "libretranslate");
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Maps LibreTranslate errors to standardized error types
|
|
136
|
+
*/
|
|
137
|
+
mapError(error) {
|
|
138
|
+
if (error instanceof TranslationError) return error;
|
|
139
|
+
const err = error;
|
|
140
|
+
return new TranslationError(err?.message || "Translation failed", err?.code || "UNKNOWN_ERROR", "libretranslate");
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
//#endregion
|
|
144
|
+
export { LibreTranslateProvider };
|
|
145
|
+
|
|
146
|
+
//# sourceMappingURL=libretranslate-oJr-l5MM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"libretranslate-oJr-l5MM.js","names":[],"sources":["../../src/providers/libretranslate.ts"],"sourcesContent":["/**\n * LibreTranslate provider implementation\n */\n\nimport type {\n LanguageDetectionResult,\n LibreTranslateOptions,\n SupportedLanguage,\n TranslationProvider,\n TranslationResult,\n} from '../shared/types';\nimport {\n AuthenticationError,\n InvalidTextError,\n TranslationError,\n UnsupportedLanguageError,\n} from '../shared/types';\nimport { getLanguageName, isValidText } from '../shared/utils';\n\n/**\n * LibreTranslate API response structures\n */\ninterface LibreTranslateTranslateResponse {\n translatedText: string;\n detectedLanguage?: {\n confidence: number;\n language: string;\n };\n}\n\ninterface LibreTranslateDetectResponse {\n confidence: number;\n language: string;\n}\n\ninterface LibreTranslateLanguage {\n code: string;\n name: string;\n}\n\n/**\n * LibreTranslate provider implementation\n */\nexport class LibreTranslateProvider implements TranslationProvider {\n private baseUrl: string;\n private apiKey?: string;\n private timeout: number;\n\n constructor(options: LibreTranslateOptions) {\n this.baseUrl = options.apiUrl || 'https://libretranslate.com';\n this.apiKey = options.apiKey;\n this.timeout = options.timeout || 30000;\n }\n\n /**\n * Translates text from source language to target language\n */\n async translate(\n text: string,\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'libretranslate');\n }\n\n try {\n const body: any = {\n q: text,\n target: targetLanguage,\n format: 'text',\n };\n\n if (sourceLanguage) {\n body.source = sourceLanguage;\n } else {\n body.source = 'auto';\n }\n\n if (this.apiKey) {\n body.api_key = this.apiKey;\n }\n\n const response = await this.fetchLibreTranslate('/translate', body);\n\n const data = response as LibreTranslateTranslateResponse;\n\n return {\n translatedText: data.translatedText,\n sourceText: text,\n sourceLanguage:\n data.detectedLanguage?.language || sourceLanguage || 'unknown',\n targetLanguage,\n confidence: data.detectedLanguage?.confidence,\n detectedSourceLanguage: !sourceLanguage,\n raw: data,\n };\n } catch (error) {\n throw this.mapError(error);\n }\n }\n\n /**\n * Detects the language of the provided text\n */\n async detectLanguage(text: string): Promise<LanguageDetectionResult> {\n if (!isValidText(text)) {\n throw new InvalidTextError('Text cannot be empty', 'libretranslate');\n }\n\n try {\n const body: any = {\n q: text,\n };\n\n if (this.apiKey) {\n body.api_key = this.apiKey;\n }\n\n const response = await this.fetchLibreTranslate('/detect', body);\n\n if (Array.isArray(response)) {\n const detections = response as LibreTranslateDetectResponse[];\n\n if (detections.length === 0) {\n throw new TranslationError(\n 'No language detected',\n 'NO_DETECTION',\n 'libretranslate',\n );\n }\n\n return {\n language: detections[0].language,\n confidence: detections[0].confidence,\n alternatives: detections.slice(1).map((d) => ({\n language: d.language,\n confidence: d.confidence,\n })),\n raw: response,\n };\n }\n\n throw new TranslationError(\n 'Invalid detection response',\n 'INVALID_RESPONSE',\n 'libretranslate',\n );\n } catch (error) {\n if (error instanceof TranslationError) {\n throw error;\n }\n throw this.mapError(error);\n }\n }\n\n /**\n * Gets the list of languages supported by this provider\n */\n async getSupportedLanguages(): Promise<SupportedLanguage[]> {\n try {\n const response = await this.fetchLibreTranslate(\n '/languages',\n undefined,\n 'GET',\n );\n\n if (Array.isArray(response)) {\n const languages = response as LibreTranslateLanguage[];\n return languages.map((lang) => ({\n code: lang.code,\n name: lang.name || getLanguageName(lang.code),\n }));\n }\n\n throw new TranslationError(\n 'Invalid languages response',\n 'INVALID_RESPONSE',\n 'libretranslate',\n );\n } catch (error) {\n if (error instanceof TranslationError) {\n throw error;\n }\n throw this.mapError(error);\n }\n }\n\n /**\n * Translates multiple texts in a single batch operation\n * Note: LibreTranslate doesn't have native batch support,\n * so we translate texts sequentially\n */\n async translateBatch(\n texts: string[],\n targetLanguage: string,\n sourceLanguage?: string,\n ): Promise<TranslationResult[]> {\n if (texts.length === 0) {\n return [];\n }\n\n // Translate each text sequentially\n const results: TranslationResult[] = [];\n for (const text of texts) {\n const result = await this.translate(text, targetLanguage, sourceLanguage);\n results.push(result);\n }\n\n return results;\n }\n\n /**\n * Makes an HTTP request to LibreTranslate API\n */\n private async fetchLibreTranslate(\n endpoint: string,\n body?: any,\n method: 'GET' | 'POST' = 'POST',\n ): Promise<any> {\n const url = `${this.baseUrl}${endpoint}`;\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const options: RequestInit = {\n method,\n signal: controller.signal,\n };\n\n if (method === 'POST' && body) {\n options.headers = {\n 'Content-Type': 'application/json',\n };\n options.body = JSON.stringify(body);\n }\n\n const response = await fetch(url, options);\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n if (response.status === 401 || response.status === 403) {\n throw new AuthenticationError('libretranslate');\n }\n\n if (response.status === 400) {\n const errorData = (await response.json().catch(() => ({}))) as any;\n if (errorData.error?.includes('language')) {\n throw new UnsupportedLanguageError(\n body.source || body.target || 'unknown',\n 'libretranslate',\n );\n }\n }\n\n throw new TranslationError(\n `HTTP ${response.status}: ${response.statusText}`,\n 'HTTP_ERROR',\n 'libretranslate',\n );\n }\n\n return await response.json();\n } catch (error) {\n clearTimeout(timeoutId);\n\n if (error instanceof TranslationError) {\n throw error;\n }\n\n if ((error as Error).name === 'AbortError') {\n throw new TranslationError(\n 'Request timeout',\n 'TIMEOUT',\n 'libretranslate',\n );\n }\n\n throw error;\n }\n }\n\n /**\n * Maps LibreTranslate errors to standardized error types\n */\n private mapError(error: unknown): TranslationError {\n if (error instanceof TranslationError) {\n return error;\n }\n\n const err = error as any;\n return new TranslationError(\n err?.message || 'Translation failed',\n err?.code || 'UNKNOWN_ERROR',\n 'libretranslate',\n );\n }\n}\n"],"mappings":";;;;;AA2CA,IAAa,yBAAb,MAAmE;CACjE;CACA;CACA;CAEA,YAAY,SAAgC;EAC1C,KAAK,UAAU,QAAQ,UAAU;EACjC,KAAK,SAAS,QAAQ;EACtB,KAAK,UAAU,QAAQ,WAAW;CACpC;;;;CAKA,MAAM,UACJ,MACA,gBACA,gBAC4B;EAC5B,IAAI,CAAC,YAAY,IAAI,GACnB,MAAM,IAAI,iBAAiB,wBAAwB,gBAAgB;EAGrE,IAAI;GACF,MAAM,OAAY;IAChB,GAAG;IACH,QAAQ;IACR,QAAQ;GACV;GAEA,IAAI,gBACF,KAAK,SAAS;QAEd,KAAK,SAAS;GAGhB,IAAI,KAAK,QACP,KAAK,UAAU,KAAK;GAKtB,MAAM,OAAO,MAFU,KAAK,oBAAoB,cAAc,IAAI;GAIlE,OAAO;IACL,gBAAgB,KAAK;IACrB,YAAY;IACZ,gBACE,KAAK,kBAAkB,YAAY,kBAAkB;IACvD;IACA,YAAY,KAAK,kBAAkB;IACnC,wBAAwB,CAAC;IACzB,KAAK;GACP;EACF,SAAS,OAAO;GACd,MAAM,KAAK,SAAS,KAAK;EAC3B;CACF;;;;CAKA,MAAM,eAAe,MAAgD;EACnE,IAAI,CAAC,YAAY,IAAI,GACnB,MAAM,IAAI,iBAA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irSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
}
|
|
17
|
-
if (existsSync(metaSrc)) {
|
|
18
|
-
copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));
|
|
19
|
-
}
|
|
5
|
+
//#region src/cli/claude-context.ts
|
|
6
|
+
/**
|
|
7
|
+
* CLI script to install agent context for @happyvertical/translator
|
|
8
|
+
* Run the published context installer binary for this package.
|
|
9
|
+
*/
|
|
10
|
+
var pkgRoot = join(dirname(fileURLToPath(import.meta.url)), "../..");
|
|
11
|
+
var targetDir = join(process.cwd(), ".claude");
|
|
12
|
+
if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
|
|
13
|
+
var pkgName = "translator";
|
|
14
|
+
var agentMdSrc = existsSync(join(pkgRoot, "AGENT.md")) ? join(pkgRoot, "AGENT.md") : join(pkgRoot, "CLAUDE.md");
|
|
15
|
+
var metaSrc = existsSync(join(pkgRoot, "metadata.json")) ? join(pkgRoot, "metadata.json") : join(pkgRoot, ".claude-meta.json");
|
|
16
|
+
if (existsSync(agentMdSrc)) copyFileSync(agentMdSrc, join(targetDir, `have-${pkgName}.md`));
|
|
17
|
+
if (existsSync(metaSrc)) copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));
|
|
20
18
|
console.log(`✓ Installed @happyvertical/${pkgName} context to .claude/`);
|
|
21
|
-
//#
|
|
19
|
+
//#endregion
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=claude-context.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-context.js","sources":["../../src/cli/claude-context.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * CLI script to install agent context for @happyvertical/translator\n * Run the published context installer binary for this package.\n */\nimport { copyFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst Dirname = dirname(fileURLToPath(import.meta.url));\nconst pkgRoot = join(Dirname, '../..');\nconst targetDir = join(process.cwd(), '.claude');\n\nif (!existsSync(targetDir)) {\n mkdirSync(targetDir, { recursive: true });\n}\n\nconst pkgName = 'translator';\nconst agentMdSrc = existsSync(join(pkgRoot, 'AGENT.md'))\n ? join(pkgRoot, 'AGENT.md')\n : join(pkgRoot, 'CLAUDE.md');\nconst metaSrc = existsSync(join(pkgRoot, 'metadata.json'))\n ? join(pkgRoot, 'metadata.json')\n : join(pkgRoot, '.claude-meta.json');\n\nif (existsSync(agentMdSrc)) {\n copyFileSync(agentMdSrc, join(targetDir, `have-${pkgName}.md`));\n}\n\nif (existsSync(metaSrc)) {\n copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));\n}\n\nconsole.log(`✓ Installed @happyvertical/${pkgName} context to .claude/`);\n"],"
|
|
1
|
+
{"version":3,"file":"claude-context.js","names":[],"sources":["../../src/cli/claude-context.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * CLI script to install agent context for @happyvertical/translator\n * Run the published context installer binary for this package.\n */\nimport { copyFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst Dirname = dirname(fileURLToPath(import.meta.url));\nconst pkgRoot = join(Dirname, '../..');\nconst targetDir = join(process.cwd(), '.claude');\n\nif (!existsSync(targetDir)) {\n mkdirSync(targetDir, { recursive: true });\n}\n\nconst pkgName = 'translator';\nconst agentMdSrc = existsSync(join(pkgRoot, 'AGENT.md'))\n ? join(pkgRoot, 'AGENT.md')\n : join(pkgRoot, 'CLAUDE.md');\nconst metaSrc = existsSync(join(pkgRoot, 'metadata.json'))\n ? join(pkgRoot, 'metadata.json')\n : join(pkgRoot, '.claude-meta.json');\n\nif (existsSync(agentMdSrc)) {\n copyFileSync(agentMdSrc, join(targetDir, `have-${pkgName}.md`));\n}\n\nif (existsSync(metaSrc)) {\n copyFileSync(metaSrc, join(targetDir, `have-${pkgName}.meta.json`));\n}\n\nconsole.log(`✓ Installed @happyvertical/${pkgName} context to .claude/`);\n"],"mappings":";;;;;;;;;AAUA,IAAM,UAAU,KADA,QAAQ,cAAc,OAAO,KAAK,GAAG,CAChC,GAAS,OAAO;AACrC,IAAM,YAAY,KAAK,QAAQ,IAAI,GAAG,SAAS;AAE/C,IAAI,CAAC,WAAW,SAAS,GACvB,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;AAG1C,IAAM,UAAU;AAChB,IAAM,aAAa,WAAW,KAAK,SAAS,UAAU,CAAC,IACnD,KAAK,SAAS,UAAU,IACxB,KAAK,SAAS,WAAW;AAC7B,IAAM,UAAU,WAAW,KAAK,SAAS,eAAe,CAAC,IACrD,KAAK,SAAS,eAAe,IAC7B,KAAK,SAAS,mBAAmB;AAErC,IAAI,WAAW,UAAU,GACvB,aAAa,YAAY,KAAK,WAAW,QAAQ,QAAQ,IAAI,CAAC;AAGhE,IAAI,WAAW,OAAO,GACpB,aAAa,SAAS,KAAK,WAAW,QAAQ,QAAQ,WAAW,CAAC;AAGpE,QAAQ,IAAI,8BAA8B,QAAQ,qBAAqB"}
|