@molecule/api-ai-translation-amazon
Provider bond · ai-translation · API (Node) · v1.1.1 · Apache-2.0
Amazon Translate provider for molecule.dev — text translation via AWS Translate
npm install @molecule/api-ai-translation-amazonnpm · Source on GitHub · Implements @molecule/api-ai-translation
How it works
@molecule/api-ai-translation-amazon is a provider bond on the API (Node) side: it implements the ai-translation core interface (@molecule/api-ai-translation) with a concrete vendor or library behind it.
Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.
import { setProvider, requireProvider } from '@molecule/api-ai-translation'
import { provider } from '@molecule/api-ai-translation-amazon'
setProvider(provider) // at startup — lazy; reads AWS_* config on first use
const { translations } = await requireProvider().translate({
text: ['{{count}} items in your cart'],
targetLang: 'de',
protect: ['{{count}}'],
})
// translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'Works with: @molecule/api-ai-translation, @molecule/api-bond, @molecule/api-secrets
Secrets: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_TRANSLATE_REGION (optional)
Reference
Amazon Translate provider for molecule.dev.
Implements the @molecule/api-ai-translation contract (translate,
getSupportedLanguages, getUsage) over Amazon Translate's TranslateText
API — one text per call, source language auto-detected by default, AWS
terminology resources usable as glossaries.
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { setProvider, requireProvider } from '@molecule/api-ai-translation'
import { provider } from '@molecule/api-ai-translation-amazon'
setProvider(provider) // at startup — lazy; reads AWS_* config on first use
const { translations } = await requireProvider().translate({
text: ['{{count}} items in your cart'],
targetLang: 'de',
protect: ['{{count}}'],
})
// translations[0].text → '{{count}} Artikel in Ihrem Warenkorb'
Type
provider
Installation
npm install @molecule/api-ai-translation-amazon @aws-sdk/client-translate @aws-sdk/credential-provider-node @molecule/api-ai-translation @molecule/api-analytics @molecule/api-bond @molecule/api-proxy-agent @molecule/api-secrets
API
Interfaces
MaskedText
A text prepared for Amazon Translate, plus what is needed to restore it.
interface MaskedText {
/** The plain text sent to Amazon Translate. */
masked: string
/** The protected substrings, in order of occurrence. */
originals: string[]
/** The numeric offset the tokens start at (collision avoidance — see `maskText`). */
offset: number
}
AwsCredentials
An explicit AWS credential pair. Omit to resolve credentials through the
AWS default chain (AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, shared
config files, or an instance role) at send time.
interface AwsCredentials {
/** The AWS access key ID. */
accessKeyId: string
/** The AWS secret access key. */
secretAccessKey: string
}
AmazonTranslateConfig
Configuration for the Amazon Translate provider.
interface AmazonTranslateConfig {
/** AWS region to call Translate in. Defaults to AWS_TRANSLATE_REGION, then AWS_REGION, then 'us-east-1'. */
region?: string
/** Endpoint URL override. Defaults to the AWS regional endpoint. */
endpoint?: string
/** Explicit credentials. Omit to use the AWS default chain. */
credentials?: AwsCredentials
}
Functions
maskText(text, protect)
Masks one text for a plain-text request.
Token numbering starts ABOVE the highest {{N}} number already present in
the caller's text, so a text that itself carries placeholder-shaped content
({{count}} is protected, but a stray literal {{0}} is not) can never
collide with the mask: restore only rewrites tokens in the masked range.
function maskText(text: string, protect: string[]): MaskedText
text— The caller's text.protect— Literal substrings to protect.
Returns: The masked text, its protected substrings, and the token offset.
unmaskText(translated, originals, offset)
Restores an Amazon Translate result: protected substrings back by index, keeping any whitespace the translator moved around the token.
Tokens outside this mask's range (a collision-avoided offset guarantees there are none) pass through untouched.
function unmaskText(translated: string, originals: string[], offset: number): string
translated— Amazon Translate's output.originals— The substringsmaskTextprotected.offset— The token offsetmaskTextused.
Returns: The restored text.
resolveRegion(config)
Resolves the region at CLIENT-CONSTRUCTION time, not import time, so a
region resolved into process.env after this module loads (late secrets
resolution via a secrets bond) is honored — the SES bond's lesson.
function resolveRegion(config?: AmazonTranslateConfig): string
config— Explicit config, when the provider was created with one.
Returns: The region to call Amazon Translate in.
buildTranslateClient(config)
Builds a Translate client from a config (or the environment when omitted).
The AWS SDK v3 builds its own https.Agent and reads no proxy variable, so
on a host whose only egress path is a proxy every call fails with a bare
connection error unless the agent is passed in via requestHandler — the
SES bond's fix, mirrored here.
function buildTranslateClient(config?: AmazonTranslateConfig): TranslateClient
config— Explicit config. Omitted keys fall back to the environment.
Returns: The configured client.
createProvider(config)
Creates an Amazon Translate provider instance.
function createProvider(config?: AmazonTranslateConfig): AITranslationProvider
config— AWS-specific configuration (region, endpoint, credentials).
Returns: An AITranslationProvider backed by Amazon Translate.
Constants
provider
The provider implementation.
const provider: AITranslationProvider
aiTranslationAmazonSecretDefinitions
Secret definitions required by the Amazon Translate bond.
const aiTranslationAmazonSecretDefinitions: SecretDefinition[]
Core Interface
Implements @molecule/api-ai-translation interface.
Bond Wiring
Setup function to register this provider with the core interface:
import { setProvider } from '@molecule/api-ai-translation'
import { provider } from '@molecule/api-ai-translation-amazon'
export function setupAiTranslationAmazon(): void {
setProvider(provider)
}
Injection Notes
Requirements
Peer dependencies:
@molecule/api-ai-translation^1.1.0@molecule/api-bond^1.0.1@molecule/api-secrets^1.0.1
Environment Variables
AWS_ACCESS_KEY_ID(required) — AWS access key ID- Setup: Create an IAM user with the needed policy (SES/S3/SQS) and create an access key under Security credentials.
- Get it here: https://console.aws.amazon.com/iam/
- Example:
AKIA...
AWS_SECRET_ACCESS_KEY(required) — AWS secret access key- Setup: Shown once when creating the IAM access key — store it immediately.
AWS_TRANSLATE_REGION(optional) — AWS Translate region — default:us-east-1- Setup: The AWS region to call Amazon Translate in. Source language 'auto' additionally needs a region where Amazon Comprehend runs.
- Example:
us-east-1
Runtime Dependencies
-
@aws-sdk/client-translate -
@aws-sdk/credential-provider-node -
@molecule/api-ai-translation -
@molecule/api-analytics -
@molecule/api-bond -
@molecule/api-proxy-agent -
@molecule/api-secrets -
Wiring: bond the lazy
providerexport once —setProvider(provider)— orsetProvider(createProvider(config?))to pass explicit config. -
Config:
AWS_ACCESS_KEY_ID+AWS_SECRET_ACCESS_KEY(required — an IAM key withtranslate:TranslateText);AWS_TRANSLATE_REGION(optional — falls back toAWS_REGION, thenus-east-1);AWS_TRANSLATE_ENDPOINT(optional endpoint override). -
Language codes are Amazon's, lowercase BCP-47 style (
de,pt,zh-TW) — not DeepL's (DE,PT-BR,ZH-HANT). Take them fromgetSupportedLanguages()(the live ListLanguages endpoint). -
Omitting
sourceLangmeansauto— Amazon detects the source language (through Amazon Comprehend), and the detection runs only in regions where Comprehend exists (us-east-1 qualifies); elsewhere passsourceLangexplicitly. -
protectis the only safe way to keep placeholders. TranslateText has no tag-handling mode, so this bond sends each protected substring as a numbered{{N}}token — numbers carry no letters a translator could case-change — and restores the original afterwards. The numbering starts above any{{N}}already in your text, so placeholder-shaped content that is NOT protected can never collide with the mask. -
formalitymaps onto Amazon'sSettings.Formality(formal/informal are supported for a subset of target languages — others reject the setting).glossaryIdmaps onto a custom terminology resource name (create it in the SAME account/region first —TerminologyNames).preserveFormatting,tagHandling,contextandmodelTypeare ignored. -
One text per call — Amazon's TranslateText takes a single string, so an array input makes one call per text (in order). Per-text cap: 10,000 bytes of UTF-8, enforced locally before any upstream call.
-
getUsage()counts this process only (characterLimitisInfinity): Amazon has no usage endpoint — spend lives in the AWS console, billed per character. -
Throttling and transient failures are retried by the AWS SDK's own retry strategy; everything else throws (tracked through
trackBondFailure). -
On hosts whose egress path is an HTTP proxy the SDK's agent is set from
@molecule/api-proxy-agentautomatically; the AWS SDK otherwise ignores proxy variables entirely.
E2E Tests
Integration checklist — drive the real UI (live preview, no mocks), adapt each item to this app's actual screens/flows, and check every box off one by one. A box you can't check is an integration bug to fix — not a skip. The sandbox has a live AI provider, so translations run for real; output is non-deterministic, so assert on the resulting LANGUAGE/meaning, never an exact string:
- Translating real text to a target language through the UI returns text ACTUALLY in that language — English→Spanish produces recognizably Spanish, not the original echoed back or left in English.
- Switching the target language (from the picker populated by getSupportedLanguages('target')) changes the output language for the same input — the same source re-translates into the newly chosen language.
- With sourceLang omitted the provider auto-detects: a known-language input comes back with the correct detectedSourceLang, and if the UI shows a detected-language label it names the right one.
- Text already in the target language is left sensible — unchanged or a valid paraphrase, never mangled, doubled, or emptied.
- Empty or untranslatable input (whitespace, emoji, a bare code snippet) is handled gracefully — a clear UI state, nothing crashes.
- A provider failure (bad key, quota exhausted, network drop) surfaces a visible error in the UI, not an unhandled 500 or a silently blank result.
- The translate call runs server-side only — the provider key never reaches the browser (check the network panel: no key in any request).