Skip to content

Programmatic API ​

All public types and classes are exported from the package root. Example: running the translate-ui step from Node.js without the CLI:

ts
import { loadI18nConfigFromFile, runTranslateUI } from 'ai-i18n-tools';

// Config must have features.translateUIStrings: true (and valid targetLocales, etc.).
const config = loadI18nConfigFromFile('ai-i18n-tools.config.json');

const summary = await runTranslateUI(config, {
  cwd: process.cwd(),
  locales: config.targetLocales,
  force: false,
  dryRun: false,
  verbose: false,
});
console.log(
  `Updated ${summary.stringsUpdated} string(s); locales touched: ${summary.localesTouched.join(', ')}`
);

Scaffold a config from Node.js. The fourth argument is the built-in preset (cwd is the third). An optional fifth argument { withReadme: true } appends the flat README docs block when the template does not already list README.md, and returns whether that block was added:

ts
import { writeInitConfigFile } from 'ai-i18n-tools';

writeInitConfigFile('ai-i18n-tools.config.json', 'uiMarkdown', process.cwd(), 'anthropic');
writeInitConfigFile('ai-i18n-tools.config.json', 'docsMarkdown', process.cwd(), 'openrouter');
writeInitConfigFile('ai-i18n-tools.config.json', 'uiPython', process.cwd(), 'openrouter', {
  withReadme: true,
});

Key exports (commonly used — see src/index.ts for the full public surface):

ExportDescription
loadI18nConfigFromFileLoad, merge, validate config from a JSON file.
parseI18nConfigValidate a raw config object.
TranslationCacheSQLite cache - instantiate with a cacheDir path.
UIStringExtractorExtract t("…") strings from JS/TS source.
collectHtmlI18nStrings / markHtmlContentScan / insert data-i18n* markers in HTML (powers extract for .html and the mark-html command).
MarkdownExtractorExtract translatable segments from markdown.
HtmlTemplateExtractorExtract and reassemble plain HTML documents (text and translatable attributes; src / href stay in place).
JsonExtractorExtract from Docusaurus JSON label files (UI catalogs, not MDX body).
SvgExtractorExtract from SVG files.
LlmClientMake translation requests to the active LLM provider (OpenRouterClient is a deprecated alias).
rankProviderModels / resolveSuggestionWeightsRank one provider's chat catalog. The index is ChrF and Arena; the quality profile sorts by that index, and the price profile walks the Pareto frontier. Does not print or write the config.
PlaceholderHandlerProtect/restore markdown syntax around translation (HTML tags, admonitions, anchors, MDX comments/JSX/braces, URLs, inline code, emphasis).
protectMdx / restoreMdxProtect/restore MDX comments, JSX tags, brace expressions, and JSX string attributes (called by PlaceholderHandler; also exported for direct use).
splitTranslatableIntoBatchesGroup segments into LLM-sized batches.
validateTranslationStructural checks after translation (async — must be awaited).
resolveDocumentationOutputPathResolve output file path for a translated document.
Glossary / GlossaryMatcherLoad and apply translation glossaries, including optional term Context notes.
loadTranslationContext / computeGuidanceFingerprintLoad glossary.contextFiles and fingerprint guidance for cache invalidation.
runTranslateUIProgrammatic translate-ui entry point.
writeInitConfigFileWrite a starter config JSON (template, cwd, a required providerKey, and optional { withReadme }). Returns { readmeBlockAdded, hasReadmeBlock }.
DEFAULT_INIT_MODELS_BY_PROVIDERStarter translationModels per built-in preset used by init -P.
PROVIDER_PRESETSBuilt-in provider preset map (baseUrl, apiKeyEnv).

Python runtime (i18n.py) ​

init -t ui-python, ui-python-gettext, and ui-python-flask write this module into the project when i18n.py is missing. It is a standard-library helper for Python 3.10 or newer. Import it from that file. The functions below are separate from the Node exports in the table above. Django projects keep Django's gettext, so ui-python-django does not write i18n.py.

Call shapes, unsafe f-strings, and per-framework locale wiring: Python applications.

FunctionBehaviour
set_locale(locale)Set the current locale. Underscores in the code are stored as hyphens (pt_BR becomes pt-BR). Returns a ContextVar token.
reset_locale(token)Restore the locale from that token. Call it in finally, including FastAPI and Flask middleware.
get_locale()Return the current locale.
set_backend(backend)Select "auto", "json", or "gettext".
get_ui_languages()Read ui-languages.json next to the flat JSON directory, or the gettext directory when flat output is off.
get_direction(locale=None)Return "rtl" or "ltr" from the manifest row for that locale (current locale when omitted).
_(message)Look up one literal, then return the catalog string or the message itself.
t(template, *, plurals=False, count=None, **values)Look up the literal, then interpolate. translate is the same function. On Python 3.14, translate(t"Hello, {name}!") keeps the template and its values. Keyword arguments override values taken from a template string.
ngettext(singular, plural, n, **values)Plural lookup, then interpolate. count is available to the format string.
pgettext(context, message, **values)Context lookup (msgctxt, or context + U+0004 + the source-language string in flat JSON), then interpolate.
streamlit_language_selector(sidebar=True, key="lang_selector")Streamlit select box. Writes st.session_state.locale and st.query_params["lang"], calls set_locale, and returns the chosen code.

.NET runtime (I18n.cs) ​

init -t ui-dotnet copies assets/dotnet/I18n.cs into the project when I18n.cs is missing. It is a dependency-free helper for .NET 6 or newer. The members below are separate from the Node exports in the table above. Call shapes and XAML markup: .NET applications.

MemberBehaviour
SetLocale(locale)Load that locale's flat JSON, walking CultureInfo.Parent when the exact file is missing. Raises LocaleChanged.
T(source, args)Look up the trimmed literal, format with string.Format, and put the source's leading and trailing whitespace back.
Tn(singular, plural, count, args)Plural lookup. {0} is the count. The catalog key is the MD5-8 of the trimmed singular plus _ and the CLDR form.
Tp(context, source, args)Look up context + U+0004 + source, then format.
N(source)Return source. Extracted so static labels can be catalogued.
Loc[source]Indexer that calls T. Loc is a static field of type StringSourceLocalizer.
Configure(options)Set the source locale when SourceLocale is non-empty. Every call replaces Strict, FlatDirectory, and OpenLocale (null clears the directory and the stream loader). Locales replaces the language list only when the array is non-null.
SupportedLocalesBuiltInLocales until a non-null Locales array is passed. Native name and English name. A null Locales array does not restore the stamp.
IsRightToLeft(locale)CultureInfo.TextInfo.IsRightToLeft.
PluralForm(locale, n)CLDR form name from the same GNU rules as .po files.

init -t ui-dotnet-resx copies I18nResx.cs instead. T, Tn, and Tp call ResourceManager with the same source-string keys. SetLocale sets CurrentUICulture and CurrentCulture. Details: Add i18n to a .NET ResourceManager app.

Released under the MIT License.