// names/translate.js translateDeepl: the reader's key goes to the right // DeepL host as a DeepL-Auth-Key header, only the prose is sent (links and // tags kept), the detected language comes back, and DeepL's refusals turn // into statuses the client can word (401 bad key, 402 quota). // Run: bun test tools/deepl-translate.test.js import { test, expect } from 'bun:test'; import { translateDeepl } from '../names/translate.js'; const fake = (status = 200, seen = []) => async (url, init) => { const body = JSON.parse(init.body); seen.push({ url, auth: init.headers.authorization, body }); if (status !== 200) return new Response('{}', { status }); return new Response(JSON.stringify({ translations: body.text.map((t) => ({ text: '[it] ' + t, detected_source_language: 'EN' })) }), { status: 200 }); }; test('a free key goes to api-free, as DeepL-Auth-Key, prose only', async () => { const seen = []; const out = await translateDeepl('Good morning everyone, look at this https://example.com/a.png #nostr', 'it', 'abcdef01-2345-6789-abcd-ef0123456789:fx', fake(200, seen)); expect(seen[0].url).toBe('https://api-free.deepl.com/v2/translate'); expect(seen[0].auth).toBe('DeepL-Auth-Key abcdef01-2345-6789-abcd-ef0123456789:fx'); expect(seen[0].body.target_lang).toBe('IT'); expect(seen[0].body.text.join(' ')).not.toContain('https://'); expect(out.source).toBe('en'); expect(out.text).toContain('[it] '); expect(out.text).toContain('https://example.com/a.png'); expect(out.text).toContain('#nostr'); }); test('a paid key goes to api.deepl.com; English means EN-US', async () => { const seen = []; await translateDeepl('Buongiorno a tutti, come state oggi?', 'en', 'abcdef01-2345-6789-abcd-ef0123456780', fake(200, seen)); expect(seen[0].url).toBe('https://api.deepl.com/v2/translate'); expect(seen[0].body.target_lang).toBe('EN-US'); }); test('refusals: bad key 401, quota 402', async () => { await expect(translateDeepl('Hello there my friends, how are you', 'it', 'abcdef01-2345-6789-abcd-ef0123456781:fx', fake(403))).rejects.toMatchObject({ status: 401 }); await expect(translateDeepl('Hello there my friends, how are you all', 'it', 'abcdef01-2345-6789-abcd-ef0123456781:fx', fake(456))).rejects.toMatchObject({ status: 402 }); await expect(translateDeepl('Hello', 'it', 'not a key')).rejects.toMatchObject({ status: 401 }); });