yapyak compiles t('Save changes') into the module that renders it. The source string is the key. On save, the yapyak plugin extracts every t() call, writes an empty stub to each locale file, and fills the stub through a translator when one is configured.
Read the reference for the project's framework before writing setup or component code:
| Framework |
Reference |
| React with Vite |
references/react.md |
| React Router |
references/react-router.md |
| TanStack Start |
references/tanstack-start.md |
| Vue with Vite |
references/vue.md |
| Nuxt |
references/nuxt.md |
| Svelte with Vite |
references/svelte.md |
| SvelteKit |
references/sveltekit.md |
| Astro |
references/astro.md |
Every YAPnnnn diagnostic, its cause, and its fix: references/diagnostics.md
Install
Requirements: Node.js 22.23.4+, Vite 8+. Frameworks: React 19+, Vue 3.4+, Svelte 5+, Astro 7+, Nuxt 4.1+, React Router 7.9+, SvelteKit 3+, TanStack Start 1.168+.
| Framework |
Install |
Build config |
Processor |
| React |
npm install yapyak @yapyak/vite @yapyak/react |
plugins: [react(), yapyak()] |
react() from @yapyak/react/processor |
| React Router |
add @yapyak/react-router |
plugins: [reactRouter(), yapyak()] |
react() |
| TanStack Start |
add @yapyak/tanstack-start |
plugins: [tanstackStart(), react(), yapyak()] |
react() |
| Vue |
npm install yapyak @yapyak/vite @yapyak/vue |
plugins: [vue(), yapyak()] |
vue() from @yapyak/vue/processor |
| Nuxt |
npx nuxi module add yapyak |
modules: ['@yapyak/nuxt'] |
nuxt() from @yapyak/nuxt/processor |
| Svelte |
npm install yapyak @yapyak/vite @yapyak/svelte |
plugins: [svelte(), yapyak()] |
svelte() from @yapyak/svelte/processor |
| SvelteKit |
add @yapyak/sveltekit |
plugins: [sveltekit(), yapyak()] |
svelte() |
| Astro |
npm install yapyak @yapyak/astro |
integrations: [yapyak()] from @yapyak/astro/integration |
astro() from @yapyak/astro/processor |
Steps, in order:
- Install the packages. Add a translator package when the project translates with a model:
@yapyak/anthropic, @yapyak/openai, @yapyak/gemini, @yapyak/ollama, or @yapyak/claude-code.
- Register the plugin in the build config, after the framework plugin.
yapyak is a named export of @yapyak/vite.
- Create
yapyak.config.ts at the project root with the processor for the framework:
import { defineConfig } from 'yapyak/config';
import { react } from '@yapyak/react/processor';
export default defineConfig({
processors: [react()]
});
- Add
.yapyak/types.d.ts and yapyak.config.ts to include in tsconfig.json. Nuxt adds the types on its own.
- Add the first target locale:
npx yapyak add sv. This creates locales/sv.json and regenerates the Locale type.
- Add
.yapyak/ to .gitignore. It holds the orphan cache; the locale files are the committed source of truth.
Register one processor per framework in the project. The built-in parser reads .ts, .tsx, .js, .jsx, .mts, .mjs, .cts, and .cjs without one.
Writing text
Wrap every user-facing string in t() from yapyak. Write the sentence in the source language exactly as the reader sees it; it is the key.
// ✓ The sentence is the key
t('Save changes');
// ✗ A synthetic key has no source string to translate
t('common.buttons.save');
Call t() inside the component or function that renders the text. A module-scope call evaluates once and never follows the active locale (YAP0055).
// ✓ Reads the active locale on every render
function SaveButton() {
return t('Save changes');
}
// ✗ Evaluates once when the module loads
const label = t('Save changes');
Write the source as a static string literal and the params as an inline object literal. The compiler reads neither from a variable.
// ✓ Static source, inline params
t('Hi {name}', { name });
// ✗ Template literal (YAP0002)
t(`Hi ${name}`);
// ✗ Variable source
t(label);
// ✗ Params in a variable (YAP0006)
t('Hi {name}', params);
Never concatenate around t() → put the moving part in a placeholder.
// ✓ One message, one placeholder
t('{count} items in your cart', { count });
// ✗ Word order differs per language
t('You have') + ' ' + count + ' ' + t('items');
Call t() in attribute positions too: aria-label={t('Pause')}, :title="t('Settings')", placeholder={t('Search')}. The attribute name is part of the call-site context the translator receives.
Placeholders
Write {name} in the source and pass the value under the same name. TypeScript derives the required keys from the source string.
| Form |
Example |
Value type |
| Plain |
t('Hi {name}', { name }) |
string | number, rendered as its string form |
| Number |
t('Total {n, number, integer}', { n }) |
number; styles decimal, integer, percent, currency <ISO 4217> |
| Date |
t('Updated {when, date, long}', { when }) |
Date or millisecond timestamp; styles short, medium, long, full |
| Time |
t('Doors open at {when, time, short}', { when }) |
Date or millisecond timestamp; styles short, medium, long, full |
| Plural |
t('{count, plural, one {# item} other {# items}}', { count }) |
number |
| Ordinal |
t('{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}', { place }) |
number |
| Select |
t('{role, select, admin {Admin panel} other {Reader view}}', { role }) |
string; a non-string is coerced with String() |
Name a placeholder with letters, digits, and underscores, starting with a letter or underscore (YAP0052). Non-ASCII letters are allowed.
Rules for plural, selectordinal, and select:
- Write an
other branch (YAP0008).
- Write
# inside a plural branch for the formatted count.
- Write
=0, =1 for an exact value; exact matches are tried before categories.
- Name plural branches with the CLDR keywords
zero, one, two, few, many, other (YAP0046).
- Write only the branches the source language uses,
one and other for English; the translator adds the branches each target locale needs.
- Nest freely: a branch is a full message and holds placeholders, plurals, and selects.
- Split a message that has become unreadable into two
t() calls and let the component pick.
- Type a
select value as a union literal so every legal value has a branch.
Format a list with format.list() outside the message and pass the result in as a placeholder. Format relative time with format.relativeTime() outside the message.
Homonyms
Split two calls with the same source and different meanings with t.as(context, source):
t.as('action', 'Open');
t.as('status', 'Open');
- Write the context as a short literal label (
action, status, noun, verb), never a variable (YAP0017).
- Use
t.as() for every occurrence of that source in the source file. Mixing t('Open') and t.as('action', 'Open') in one file is an error (YAP0018).
- Use plain
t() when the source has one meaning. A lone context is an error (YAP0019).
Forced locale
- Write
t.in(locale, source) for the translation in a forced locale regardless of the active one. The locale argument is typed against Locale.
- Chain
t.in('sv').as('action', 'Open') or t.as('action').in('sv', 'Open') when both apply.
- Complete the chain in one expression. A chain stored in a variable is an error (
YAP0020).
Rich text
Write tags inside the source and bind each tag to a handler in <RichText> from the framework's adapter package.
t('Read our <link>privacy policy</link> for details.');
t('Line one<br/>line two');
| Tag |
Form |
Handler |
| Pair |
<link>…</link> |
Receives the wrapped children |
| Void |
<br/> |
Receives nothing |
- Start a tag name with a letter and continue with letters or digits.
- Name a tag by meaning (
link, strong, price), never by HTML element; the element belongs in the handler.
- Bind a handler for every tag in the source.
- Never write attributes on a tag → put the
href in the handler.
- Walk the structure with
parseRichText(value) from yapyak, which returns RichTextNode[], when <RichText> does not fit.
Take the handler shape from the framework's reference file.
Formatting outside messages
Format values outside a message with format from yapyak. Every call reads the active locale.
| Method |
Backed by |
Note |
format.number(value, options) |
Intl.NumberFormat |
style: 'currency' requires currency; style: 'unit' requires unit |
format.dateTime(value, options) |
Intl.DateTimeFormat |
dateStyle and timeStyle presets, or field options |
format.list(items, options) |
Intl.ListFormat |
Run each item through t() first |
format.relativeTime(value, unit, options) |
Intl.RelativeTimeFormat |
Negative is past; numeric: 'auto' gives yesterday |
format.displayName(code, type, options) |
Intl.DisplayNames |
type is language, region, script, currency, calendar, or dateTimeField |
format.in(locale) |
|
Returns a format scoped to a forced locale |
- Use
format.* for a value outside a message and an ICU sub-format for a value inside one.
- Type a currency code as
Currency from yapyak; narrow user input with isCurrency(value).
- Label a locale switcher with
format.in(value).displayName(value, 'language'), never with a t() call per language.
- An unsupported currency, unit, time zone, or display-name code renders a fallback instead of throwing and reports
YAP0035, YAP0036, YAP0037, or YAP0056.
The active locale
A locale is the BCP 47 tag of a file in localesDir: sv for locales/sv.json, en-GB for locales/en-GB.json. Write tags as lowercase-Titlecase-UPPERCASE (zh-Hant-TW). The Locale type is the union of the files on disk and refreshes on yapyak add.
The active locale resolves in this order, first value wins: a persisted choice, a detected locale when detectUserLocale is on, then defaultLocale.
Export from yapyak |
Use |
getLocale() |
The active locale, outside components |
setLocale(locale) |
Switch and persist; ignored with a warning for an unknown value (YAP0028) |
locales |
Every added locale, for a switcher |
defaultLocale |
The locale when no persisted or detected locale matches |
isLocale(value) |
Type guard for a canonical string |
parseLocale(value) |
Normalizes casing, returns Locale or undefined |
getLocaleFallbackChain(locale) |
['zh-Hant-TW', 'zh-Hant', 'zh']; defaultLocale is not appended |
getTextDirection(locale) |
'rtl' or 'ltr' for <html dir> |
Read and switch the locale inside a component through the framework binding; never call getLocale() or setLocale() there.
| Framework |
Binding |
| React |
const [locale, setLocale] = useLocale(); useTextDirection() |
| Vue, Nuxt |
locale ref (locale.value, or locale in a template); textDirection ref |
| Svelte, SvelteKit |
locale.current; textDirection.current |
| Astro |
getLocale() in frontmatter; the middleware binds it per request |
Narrow a string from a URL, a form, or a cookie with isLocale() or parseLocale() before setLocale().
yapyak.config.ts
Every field is optional. Export the result of defineConfig from yapyak/config.
| Field |
Default |
Sets |
sourceLocale |
defaultLocale |
The language the source strings are written in. Set it only when it differs from defaultLocale |
defaultLocale |
'en' |
The locale when no persisted or detected locale matches |
localesDir |
'locales' |
The directory of locale files, relative to the project root |
include |
['.'] |
Directories, globs, or RegExp to scan; replaces the default |
exclude |
tests, *.d.ts, node_modules, dist, build, coverage, yapyak.config.* |
Files to skip; replaces the default. Extend with [...DEFAULT_EXCLUDE, '**/*.vendor.ts'] |
processors |
[] |
One per framework |
translator |
none |
The translator that fills stubs |
autoTranslateThreshold |
20 |
New strings in one save above which the save loop writes stubs but skips the translator. 0 turns auto-translation off |
preserveTranslationsOnSourceEdit |
true without a translator, false with one |
Keep the translation when a source string is edited in place |
persistence |
'none' |
Where the active locale is stored between page loads |
detectUserLocale |
false |
Match Accept-Language on the server and navigator.languages in the browser on a first visit |
syncHtmlAttributes |
false |
Keep <html lang> and <html dir> in step with the active locale on every change |
| Processor |
Option |
Use |
react({ rsc: true }) |
rsc |
React Server Components: only 'use client' files subscribe to the locale |
nuxt({ explicitImports: true }) |
explicitImports |
Another global t exists in the project |
vue(), svelte(), astro() |
none |
|
Persistence
| Value |
Options |
Fits |
'none' |
|
Kiosk, development build, locale carried by another system. A reload returns to defaultLocale |
'cookie' |
{ type: 'cookie', name: 'locale', secure: false } |
SSR apps. The adapter reads the cookie per request; setLocale() on the server buffers a Set-Cookie |
'local-storage' |
{ type: 'local-storage', key: 'locale' } |
Client-only apps. Under SSR the first render uses defaultLocale and flips after hydration |
'url' |
{ type: 'url', match: /[?&]lang=(?<locale>[^&]+)/ } |
Locale in the path (/sv/settings, the default reads the first segment) or in a query string |
- Under
'url', switch by navigating. setLocale() is a no-op and reports YAP0026.
- Set
secure: true on the cookie in production only; on plain HTTP the browser refuses the write.
Fixed-locale builds
- Set
fixedLocale in the build config, never in yapyak.config.ts. Every t() compiles to the literal of that locale and the runtime disappears from the bundle.
- Drive a CI matrix from an environment variable. With the variable unset, the build is a normal multi-locale build.
- Pass an added locale; the build throws otherwise.
| Framework |
Where |
| Vite (React, Vue, Svelte, React Router, SvelteKit, TanStack Start) |
yapyak({ fixedLocale: process.env.YAPYAK_LOCALE }) in vite.config.ts |
| Astro |
yapyak({ fixedLocale: process.env.YAPYAK_LOCALE }) in astro.config.ts |
| Nuxt |
yapyak: { fixedLocale: process.env.YAPYAK_LOCALE } in nuxt.config.ts |
Locale files
One JSON file per target locale in localesDir. The source language has no file. Entries nest under the source file's path, then the source string:
{
"src/components/save-button.tsx": {
"Save changes": "Spara ändringar"
}
}
A homonym nests its contexts under the source:
{
"src/components/dialog.tsx": {
"Open": {
"action": "Öppna",
"status": "Öppen"
}
}
}
- An empty string is an empty stub. The runtime renders the source string for it.
- Hand-edit a value to correct or replace a translation. The running app updates through HMR.
- Keep every placeholder, tag, and ICU structure of the source in the translation (
YAP0010, YAP0011, YAP0012, YAP0038, YAP0045, YAP0050, YAP0051). Placeholder names stay fixed; their position in the sentence is free.
- Never edit a key → change the source string in the component; the compiler rewrites the key.
- Never add an entry by hand → write the
t() call; the save loop or yapyak translate creates the stub.
- Renames and moves of source files restore translations from the orphan cache in
.yapyak/orphans.json on the next save. Deleting .yapyak/ loses nothing committed.
- Orphans stay in the locale file until
yapyak clean --write removes them.
Fill empty stubs by hand only when the project has no translator or the user asks for it.
Translators
A translator fills empty stubs on save and in yapyak translate. Requests go from the developer's machine to the provider. Set one in yapyak.config.ts:
import { defineConfig } from 'yapyak/config';
import { anthropic } from '@yapyak/anthropic';
export default defineConfig({
translator: anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
glossary: { cart: { sv: 'kundvagn' } },
voice: 'Concise and friendly'
})
});
| Package |
Factory |
Key |
Defaults that differ |
@yapyak/anthropic |
anthropic({ apiKey }) |
ANTHROPIC_API_KEY |
|
@yapyak/openai |
openai({ apiKey }) |
OPENAI_API_KEY |
Extras seed, organization, user; other OpenAI-compatible endpoints through endpoint and headers |
@yapyak/gemini |
gemini({ apiKey }) |
GEMINI_API_KEY |
batchSize: 15 |
@yapyak/ollama |
ollama() |
none |
endpoint: 'http://localhost:11434/api/generate', model: 'llama3.1', timeout: 120_000, maxRetries: 1, batchSize: 8 |
@yapyak/claude-code |
claudeCode() |
the signed-in claude CLI |
concurrency: 2, timeout: 120_000; no HTTP options; model falls back to the CLI's |
| Shared option |
Default |
Sets |
model |
per provider |
Model identifier |
voice |
none |
One or two sentences of tone guidance |
glossary |
{} |
Record<source term, Record<locale, translation>>; pinned brand names, domain terms, and words the model gets wrong |
context |
'minimal' |
'none' sends the source string only; 'rich' adds the surrounding code |
examples |
5, 0 under context: 'none' |
Existing translations sent per request as style reference |
temperature |
0.2 |
Sampling temperature |
maxTokens |
per provider |
Output token cap |
timeout |
30_000 |
Per-request timeout in milliseconds |
maxRetries |
2 |
Retries on 408, 429, 5xx, and network failures |
batchSize |
25 |
Source strings per request |
concurrency |
5 |
Parallel requests |
headers |
{} |
Extra HTTP headers |
endpoint |
per provider |
API URL |
- The
t.as() context is sent at every context level.
- A voice or glossary change affects new translations only. Run
yapyak translate --force or yapyak retranslate "<source>" to propagate it.
- Pick the translator by environment when CI has no signed-in CLI:
process.env.CI ? anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }) : claudeCode().
A custom translator is createTranslator({ id, translate }) from yapyak/translator:
translate({ items, signal, sourceLocale, targetLocales }) returns one object per item, in item order, keyed by every target locale.
- Forward
signal to the request.
- Throw
TranslatorAuthError, TranslatorRateLimitError, TranslatorTimeoutError, TranslatorNetworkError, TranslatorSafetyError, TranslatorInvalidResponseError, or TranslatorTruncatedError from yapyak/translator.
- Retry inside the callback. yapyak runs it once.
CLI
Run through the package manager: npx yapyak <command>, pnpm yapyak <command>, bunx yapyak <command>. Every command except info walks the source files first, so a t() call added without the dev server running is still found.
| Command |
Does |
Exit code |
yapyak add <locale> [<locale>...] |
Creates the locale file, fills it through the translator, regenerates the Locale type. Several tags in one run share requests |
non-zero on an unrecognized tag |
yapyak translate [<locale>] [--force] |
Fills empty stubs. --force re-translates every entry and overwrites hand-edits |
1 without a translator |
yapyak retranslate "<source>" [--locale <code>] [--as <ctx>] [--file <path>] |
Re-translates one source string; the flags compose |
0 when nothing matches |
yapyak status [--json] |
Coverage per locale |
1 when a translation is missing |
yapyak check |
Missing translations, compile-time diagnostics, ICU mismatches |
1 on any finding |
yapyak clean [--write] |
Lists orphans; --write deletes them |
|
yapyak export [<locale>...] [--out <path>] [--split] |
Snapshot keyed by locale, then path, then source |
non-zero on an unknown tag |
yapyak info |
Versions for a bug report |
0 |
Boolean flags accept =: --write=false. NO_COLOR and CI strip color.
CI order: yapyak translate with the provider key in the environment, then yapyak check, then the build. check never calls the translator.
Working in a project
- Write the
t() call in the component. With the dev server running, the save writes the stub and the translator fills it. Without it, the CLI finds the call.
- Run
npx yapyak check before finishing. Fix every reported YAPnnnn with references/diagnostics.md.
- Run
npx yapyak translate when check reports missing translations and the project has a translator. Fill the stubs by hand when it has none.
- Commit the locale files with the code. They are the source of truth;
.yapyak/ is a cache.
- Run
npx yapyak clean after removing components, and --write once the list is right.
Diagnostics an agent most often triggers:
| Code |
Cause |
Fix |
YAP0002 |
Template literal source |
t('Hi {name}', { name }) |
YAP0004, YAP0005, YAP0049 |
Params do not match the placeholders |
Match the keys to the {names} in the source |
YAP0006 |
Params in a variable |
Inline object literal |
YAP0008 |
No other branch |
Add other {...} |
YAP0018 |
t() and t.as() for one source in one file |
t.as() on every occurrence |
YAP0020 |
Chain stored in a variable |
Complete t.in() or t.as() inline |
YAP0046 |
Branch name is not a CLDR keyword |
zero, one, two, few, many, other, or =N |
YAP0055 |
t() at module scope |
Move the call into the function that renders it |
YAP0022 |
getLocale() on the server without an adapter |
Register the SSR adapter from the framework reference |
1---2name: yapyak3description: "yapyak, an i18n compiler with a small runtime: t() with the source string as the key, ICU plurals and selects, rich text, format.* for numbers, dates and lists, locale switching and persistence, yapyak.config.ts, translators, the yapyak CLI, and YAPnnnn diagnostics. Use when adding or editing user-facing text in a project that depends on yapyak, when setting up @yapyak/vite, @yapyak/react, @yapyak/vue, @yapyak/svelte, @yapyak/astro, @yapyak/nuxt, @yapyak/react-router, @yapyak/sveltekit or @yapyak/tanstack-start, or when a YAP diagnostic fires."4license: MIT5metadata:6 source: https://skillmd.com/skills/tuyv/yapyak7 upstream: https://github.com/yapyak/yapyak/tree/main/skills/yapyak8---910yapyak compiles `t('Save changes')` into the module that renders it. The source string is the key. On save, the yapyak plugin extracts every `t()` call, writes an empty stub to each locale file, and fills the stub through a translator when one is configured.1112Read the reference for the project's framework before writing setup or component code:1314| Framework | Reference |15| --- | --- |16| React with Vite | [references/react.md](references/react.md) |17| React Router | [references/react-router.md](references/react-router.md) |18| TanStack Start | [references/tanstack-start.md](references/tanstack-start.md) |19| Vue with Vite | [references/vue.md](references/vue.md) |20| Nuxt | [references/nuxt.md](references/nuxt.md) |21| Svelte with Vite | [references/svelte.md](references/svelte.md) |22| SvelteKit | [references/sveltekit.md](references/sveltekit.md) |23| Astro | [references/astro.md](references/astro.md) |2425Every `YAPnnnn` diagnostic, its cause, and its fix: [references/diagnostics.md](references/diagnostics.md)2627## Install2829Requirements: Node.js 22.23.4+, Vite 8+. Frameworks: React 19+, Vue 3.4+, Svelte 5+, Astro 7+, Nuxt 4.1+, React Router 7.9+, SvelteKit 3+, TanStack Start 1.168+.3031| Framework | Install | Build config | Processor |32| --- | --- | --- | --- |33| React | `npm install yapyak @yapyak/vite @yapyak/react` | `plugins: [react(), yapyak()]` | `react()` from `@yapyak/react/processor` |34| React Router | add `@yapyak/react-router` | `plugins: [reactRouter(), yapyak()]` | `react()` |35| TanStack Start | add `@yapyak/tanstack-start` | `plugins: [tanstackStart(), react(), yapyak()]` | `react()` |36| Vue | `npm install yapyak @yapyak/vite @yapyak/vue` | `plugins: [vue(), yapyak()]` | `vue()` from `@yapyak/vue/processor` |37| Nuxt | `npx nuxi module add yapyak` | `modules: ['@yapyak/nuxt']` | `nuxt()` from `@yapyak/nuxt/processor` |38| Svelte | `npm install yapyak @yapyak/vite @yapyak/svelte` | `plugins: [svelte(), yapyak()]` | `svelte()` from `@yapyak/svelte/processor` |39| SvelteKit | add `@yapyak/sveltekit` | `plugins: [sveltekit(), yapyak()]` | `svelte()` |40| Astro | `npm install yapyak @yapyak/astro` | `integrations: [yapyak()]` from `@yapyak/astro/integration` | `astro()` from `@yapyak/astro/processor` |4142Steps, in order:43441. Install the packages. Add a translator package when the project translates with a model: `@yapyak/anthropic`, `@yapyak/openai`, `@yapyak/gemini`, `@yapyak/ollama`, or `@yapyak/claude-code`.452. Register the plugin in the build config, after the framework plugin. `yapyak` is a named export of `@yapyak/vite`.463. Create `yapyak.config.ts` at the project root with the processor for the framework:4748```ts [yapyak.config.ts]49import { defineConfig } from 'yapyak/config';50import { react } from '@yapyak/react/processor';5152export default defineConfig({53 processors: [react()]54});55```56574. Add `.yapyak/types.d.ts` and `yapyak.config.ts` to `include` in `tsconfig.json`. Nuxt adds the types on its own.585. Add the first target locale: `npx yapyak add sv`. This creates `locales/sv.json` and regenerates the `Locale` type.596. Add `.yapyak/` to `.gitignore`. It holds the orphan cache; the locale files are the committed source of truth.6061Register one processor per framework in the project. The built-in parser reads `.ts`, `.tsx`, `.js`, `.jsx`, `.mts`, `.mjs`, `.cts`, and `.cjs` without one.6263## Writing text6465Wrap every user-facing string in `t()` from `yapyak`. Write the sentence in the source language exactly as the reader sees it; it is the key.6667```ts68// ✓ The sentence is the key69t('Save changes');7071// ✗ A synthetic key has no source string to translate72t('common.buttons.save');73```7475Call `t()` inside the component or function that renders the text. A module-scope call evaluates once and never follows the active locale (`YAP0055`).7677```ts78// ✓ Reads the active locale on every render79function SaveButton() {80 return t('Save changes');81}8283// ✗ Evaluates once when the module loads84const label = t('Save changes');85```8687Write the source as a static string literal and the params as an inline object literal. The compiler reads neither from a variable.8889```ts90// ✓ Static source, inline params91t('Hi {name}', { name });9293// ✗ Template literal (YAP0002)94t(`Hi ${name}`);9596// ✗ Variable source97t(label);9899// ✗ Params in a variable (YAP0006)100t('Hi {name}', params);101```102103Never concatenate around `t()` → put the moving part in a placeholder.104105```ts106// ✓ One message, one placeholder107t('{count} items in your cart', { count });108109// ✗ Word order differs per language110t('You have') + ' ' + count + ' ' + t('items');111```112113Call `t()` in attribute positions too: `aria-label={t('Pause')}`, `:title="t('Settings')"`, `placeholder={t('Search')}`. The attribute name is part of the call-site context the translator receives.114115### Placeholders116117Write `{name}` in the source and pass the value under the same name. TypeScript derives the required keys from the source string.118119| Form | Example | Value type |120| --- | --- | --- |121| Plain | `t('Hi {name}', { name })` | `string \| number`, rendered as its string form |122| Number | `t('Total {n, number, integer}', { n })` | `number`; styles `decimal`, `integer`, `percent`, `currency <ISO 4217>` |123| Date | `t('Updated {when, date, long}', { when })` | `Date` or millisecond timestamp; styles `short`, `medium`, `long`, `full` |124| Time | `t('Doors open at {when, time, short}', { when })` | `Date` or millisecond timestamp; styles `short`, `medium`, `long`, `full` |125| Plural | `t('{count, plural, one {# item} other {# items}}', { count })` | `number` |126| Ordinal | `t('{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}', { place })` | `number` |127| Select | `t('{role, select, admin {Admin panel} other {Reader view}}', { role })` | `string`; a non-string is coerced with `String()` |128129Name a placeholder with letters, digits, and underscores, starting with a letter or underscore (`YAP0052`). Non-ASCII letters are allowed.130131Rules for `plural`, `selectordinal`, and `select`:132133- Write an `other` branch (`YAP0008`).134- Write `#` inside a plural branch for the formatted count.135- Write `=0`, `=1` for an exact value; exact matches are tried before categories.136- Name plural branches with the CLDR keywords `zero`, `one`, `two`, `few`, `many`, `other` (`YAP0046`).137- Write only the branches the source language uses, `one` and `other` for English; the translator adds the branches each target locale needs.138- Nest freely: a branch is a full message and holds placeholders, plurals, and selects.139- Split a message that has become unreadable into two `t()` calls and let the component pick.140- Type a `select` value as a union literal so every legal value has a branch.141142Format a list with `format.list()` outside the message and pass the result in as a placeholder. Format relative time with `format.relativeTime()` outside the message.143144### Homonyms145146Split two calls with the same source and different meanings with `t.as(context, source)`:147148```ts149t.as('action', 'Open');150151t.as('status', 'Open');152```153154- Write the context as a short literal label (`action`, `status`, `noun`, `verb`), never a variable (`YAP0017`).155- Use `t.as()` for every occurrence of that source in the source file. Mixing `t('Open')` and `t.as('action', 'Open')` in one file is an error (`YAP0018`).156- Use plain `t()` when the source has one meaning. A lone context is an error (`YAP0019`).157158### Forced locale159160- Write `t.in(locale, source)` for the translation in a forced locale regardless of the active one. The locale argument is typed against `Locale`.161- Chain `t.in('sv').as('action', 'Open')` or `t.as('action').in('sv', 'Open')` when both apply.162- Complete the chain in one expression. A chain stored in a variable is an error (`YAP0020`).163164### Rich text165166Write tags inside the source and bind each tag to a handler in `<RichText>` from the framework's adapter package.167168```ts169t('Read our <link>privacy policy</link> for details.');170171t('Line one<br/>line two');172```173174| Tag | Form | Handler |175| --- | --- | --- |176| Pair | `<link>…</link>` | Receives the wrapped children |177| Void | `<br/>` | Receives nothing |178179- Start a tag name with a letter and continue with letters or digits.180- Name a tag by meaning (`link`, `strong`, `price`), never by HTML element; the element belongs in the handler.181- Bind a handler for every tag in the source.182- Never write attributes on a tag → put the `href` in the handler.183- Walk the structure with `parseRichText(value)` from `yapyak`, which returns `RichTextNode[]`, when `<RichText>` does not fit.184185Take the handler shape from the framework's reference file.186187## Formatting outside messages188189Format values outside a message with `format` from `yapyak`. Every call reads the active locale.190191| Method | Backed by | Note |192| --- | --- | --- |193| `format.number(value, options)` | `Intl.NumberFormat` | `style: 'currency'` requires `currency`; `style: 'unit'` requires `unit` |194| `format.dateTime(value, options)` | `Intl.DateTimeFormat` | `dateStyle` and `timeStyle` presets, or field options |195| `format.list(items, options)` | `Intl.ListFormat` | Run each item through `t()` first |196| `format.relativeTime(value, unit, options)` | `Intl.RelativeTimeFormat` | Negative is past; `numeric: 'auto'` gives `yesterday` |197| `format.displayName(code, type, options)` | `Intl.DisplayNames` | `type` is `language`, `region`, `script`, `currency`, `calendar`, or `dateTimeField` |198| `format.in(locale)` | | Returns a `format` scoped to a forced locale |199200- Use `format.*` for a value outside a message and an ICU sub-format for a value inside one.201- Type a currency code as `Currency` from `yapyak`; narrow user input with `isCurrency(value)`.202- Label a locale switcher with `format.in(value).displayName(value, 'language')`, never with a `t()` call per language.203- An unsupported currency, unit, time zone, or display-name code renders a fallback instead of throwing and reports `YAP0035`, `YAP0036`, `YAP0037`, or `YAP0056`.204205## The active locale206207A locale is the BCP 47 tag of a file in `localesDir`: `sv` for `locales/sv.json`, `en-GB` for `locales/en-GB.json`. Write tags as `lowercase-Titlecase-UPPERCASE` (`zh-Hant-TW`). The `Locale` type is the union of the files on disk and refreshes on `yapyak add`.208209The active locale resolves in this order, first value wins: a persisted choice, a detected locale when `detectUserLocale` is on, then `defaultLocale`.210211| Export from `yapyak` | Use |212| --- | --- |213| `getLocale()` | The active locale, outside components |214| `setLocale(locale)` | Switch and persist; ignored with a warning for an unknown value (`YAP0028`) |215| `locales` | Every added locale, for a switcher |216| `defaultLocale` | The locale when no persisted or detected locale matches |217| `isLocale(value)` | Type guard for a canonical string |218| `parseLocale(value)` | Normalizes casing, returns `Locale` or `undefined` |219| `getLocaleFallbackChain(locale)` | `['zh-Hant-TW', 'zh-Hant', 'zh']`; `defaultLocale` is not appended |220| `getTextDirection(locale)` | `'rtl'` or `'ltr'` for `<html dir>` |221222Read and switch the locale inside a component through the framework binding; never call `getLocale()` or `setLocale()` there.223224| Framework | Binding |225| --- | --- |226| React | `const [locale, setLocale] = useLocale()`; `useTextDirection()` |227| Vue, Nuxt | `locale` ref (`locale.value`, or `locale` in a template); `textDirection` ref |228| Svelte, SvelteKit | `locale.current`; `textDirection.current` |229| Astro | `getLocale()` in frontmatter; the middleware binds it per request |230231Narrow a string from a URL, a form, or a cookie with `isLocale()` or `parseLocale()` before `setLocale()`.232233## `yapyak.config.ts`234235Every field is optional. Export the result of `defineConfig` from `yapyak/config`.236237| Field | Default | Sets |238| --- | --- | --- |239| `sourceLocale` | `defaultLocale` | The language the source strings are written in. Set it only when it differs from `defaultLocale` |240| `defaultLocale` | `'en'` | The locale when no persisted or detected locale matches |241| `localesDir` | `'locales'` | The directory of locale files, relative to the project root |242| `include` | `['.']` | Directories, globs, or `RegExp` to scan; replaces the default |243| `exclude` | tests, `*.d.ts`, `node_modules`, `dist`, `build`, `coverage`, `yapyak.config.*` | Files to skip; replaces the default. Extend with `[...DEFAULT_EXCLUDE, '**/*.vendor.ts']` |244| `processors` | `[]` | One per framework |245| `translator` | none | The translator that fills stubs |246| `autoTranslateThreshold` | `20` | New strings in one save above which the save loop writes stubs but skips the translator. `0` turns auto-translation off |247| `preserveTranslationsOnSourceEdit` | `true` without a translator, `false` with one | Keep the translation when a source string is edited in place |248| `persistence` | `'none'` | Where the active locale is stored between page loads |249| `detectUserLocale` | `false` | Match `Accept-Language` on the server and `navigator.languages` in the browser on a first visit |250| `syncHtmlAttributes` | `false` | Keep `<html lang>` and `<html dir>` in step with the active locale on every change |251252| Processor | Option | Use |253| --- | --- | --- |254| `react({ rsc: true })` | `rsc` | React Server Components: only `'use client'` files subscribe to the locale |255| `nuxt({ explicitImports: true })` | `explicitImports` | Another global `t` exists in the project |256| `vue()`, `svelte()`, `astro()` | none | |257258### Persistence259260| Value | Options | Fits |261| --- | --- | --- |262| `'none'` | | Kiosk, development build, locale carried by another system. A reload returns to `defaultLocale` |263| `'cookie'` | `{ type: 'cookie', name: 'locale', secure: false }` | SSR apps. The adapter reads the cookie per request; `setLocale()` on the server buffers a `Set-Cookie` |264| `'local-storage'` | `{ type: 'local-storage', key: 'locale' }` | Client-only apps. Under SSR the first render uses `defaultLocale` and flips after hydration |265| `'url'` | `{ type: 'url', match: /[?&]lang=(?<locale>[^&]+)/ }` | Locale in the path (`/sv/settings`, the default reads the first segment) or in a query string |266267- Under `'url'`, switch by navigating. `setLocale()` is a no-op and reports `YAP0026`.268- Set `secure: true` on the cookie in production only; on plain HTTP the browser refuses the write.269270### Fixed-locale builds271272- Set `fixedLocale` in the build config, never in `yapyak.config.ts`. Every `t()` compiles to the literal of that locale and the runtime disappears from the bundle.273- Drive a CI matrix from an environment variable. With the variable unset, the build is a normal multi-locale build.274- Pass an added locale; the build throws otherwise.275276| Framework | Where |277| --- | --- |278| Vite (React, Vue, Svelte, React Router, SvelteKit, TanStack Start) | `yapyak({ fixedLocale: process.env.YAPYAK_LOCALE })` in `vite.config.ts` |279| Astro | `yapyak({ fixedLocale: process.env.YAPYAK_LOCALE })` in `astro.config.ts` |280| Nuxt | `yapyak: { fixedLocale: process.env.YAPYAK_LOCALE }` in `nuxt.config.ts` |281282## Locale files283284One JSON file per target locale in `localesDir`. The source language has no file. Entries nest under the source file's path, then the source string:285286```json287{288 "src/components/save-button.tsx": {289 "Save changes": "Spara ändringar"290 }291}292```293294A homonym nests its contexts under the source:295296```json297{298 "src/components/dialog.tsx": {299 "Open": {300 "action": "Öppna",301 "status": "Öppen"302 }303 }304}305```306307- An empty string is an empty stub. The runtime renders the source string for it.308- Hand-edit a value to correct or replace a translation. The running app updates through HMR.309- Keep every placeholder, tag, and ICU structure of the source in the translation (`YAP0010`, `YAP0011`, `YAP0012`, `YAP0038`, `YAP0045`, `YAP0050`, `YAP0051`). Placeholder names stay fixed; their position in the sentence is free.310- Never edit a key → change the source string in the component; the compiler rewrites the key.311- Never add an entry by hand → write the `t()` call; the save loop or `yapyak translate` creates the stub.312- Renames and moves of source files restore translations from the orphan cache in `.yapyak/orphans.json` on the next save. Deleting `.yapyak/` loses nothing committed.313- Orphans stay in the locale file until `yapyak clean --write` removes them.314315Fill empty stubs by hand only when the project has no translator or the user asks for it.316317## Translators318319A translator fills empty stubs on save and in `yapyak translate`. Requests go from the developer's machine to the provider. Set one in `yapyak.config.ts`:320321```ts [yapyak.config.ts]322import { defineConfig } from 'yapyak/config';323import { anthropic } from '@yapyak/anthropic';324325export default defineConfig({326 translator: anthropic({327 apiKey: process.env.ANTHROPIC_API_KEY,328 glossary: { cart: { sv: 'kundvagn' } },329 voice: 'Concise and friendly'330 })331});332```333334| Package | Factory | Key | Defaults that differ |335| --- | --- | --- | --- |336| `@yapyak/anthropic` | `anthropic({ apiKey })` | `ANTHROPIC_API_KEY` | |337| `@yapyak/openai` | `openai({ apiKey })` | `OPENAI_API_KEY` | Extras `seed`, `organization`, `user`; other OpenAI-compatible endpoints through `endpoint` and `headers` |338| `@yapyak/gemini` | `gemini({ apiKey })` | `GEMINI_API_KEY` | `batchSize: 15` |339| `@yapyak/ollama` | `ollama()` | none | `endpoint: 'http://localhost:11434/api/generate'`, `model: 'llama3.1'`, `timeout: 120_000`, `maxRetries: 1`, `batchSize: 8` |340| `@yapyak/claude-code` | `claudeCode()` | the signed-in `claude` CLI | `concurrency: 2`, `timeout: 120_000`; no HTTP options; `model` falls back to the CLI's |341342| Shared option | Default | Sets |343| --- | --- | --- |344| `model` | per provider | Model identifier |345| `voice` | none | One or two sentences of tone guidance |346| `glossary` | `{}` | `Record<source term, Record<locale, translation>>`; pinned brand names, domain terms, and words the model gets wrong |347| `context` | `'minimal'` | `'none'` sends the source string only; `'rich'` adds the surrounding code |348| `examples` | `5`, `0` under `context: 'none'` | Existing translations sent per request as style reference |349| `temperature` | `0.2` | Sampling temperature |350| `maxTokens` | per provider | Output token cap |351| `timeout` | `30_000` | Per-request timeout in milliseconds |352| `maxRetries` | `2` | Retries on 408, 429, 5xx, and network failures |353| `batchSize` | `25` | Source strings per request |354| `concurrency` | `5` | Parallel requests |355| `headers` | `{}` | Extra HTTP headers |356| `endpoint` | per provider | API URL |357358- The `t.as()` context is sent at every `context` level.359- A voice or glossary change affects new translations only. Run `yapyak translate --force` or `yapyak retranslate "<source>"` to propagate it.360- Pick the translator by environment when CI has no signed-in CLI: `process.env.CI ? anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }) : claudeCode()`.361362A custom translator is `createTranslator({ id, translate })` from `yapyak/translator`:363364- `translate({ items, signal, sourceLocale, targetLocales })` returns one object per item, in item order, keyed by every target locale.365- Forward `signal` to the request.366- Throw `TranslatorAuthError`, `TranslatorRateLimitError`, `TranslatorTimeoutError`, `TranslatorNetworkError`, `TranslatorSafetyError`, `TranslatorInvalidResponseError`, or `TranslatorTruncatedError` from `yapyak/translator`.367- Retry inside the callback. yapyak runs it once.368369## CLI370371Run through the package manager: `npx yapyak <command>`, `pnpm yapyak <command>`, `bunx yapyak <command>`. Every command except `info` walks the source files first, so a `t()` call added without the dev server running is still found.372373| Command | Does | Exit code |374| --- | --- | --- |375| `yapyak add <locale> [<locale>...]` | Creates the locale file, fills it through the translator, regenerates the `Locale` type. Several tags in one run share requests | non-zero on an unrecognized tag |376| `yapyak translate [<locale>] [--force]` | Fills empty stubs. `--force` re-translates every entry and overwrites hand-edits | `1` without a translator |377| `yapyak retranslate "<source>" [--locale <code>] [--as <ctx>] [--file <path>]` | Re-translates one source string; the flags compose | `0` when nothing matches |378| `yapyak status [--json]` | Coverage per locale | `1` when a translation is missing |379| `yapyak check` | Missing translations, compile-time diagnostics, ICU mismatches | `1` on any finding |380| `yapyak clean [--write]` | Lists orphans; `--write` deletes them | |381| `yapyak export [<locale>...] [--out <path>] [--split]` | Snapshot keyed by locale, then path, then source | non-zero on an unknown tag |382| `yapyak info` | Versions for a bug report | `0` |383384Boolean flags accept `=`: `--write=false`. `NO_COLOR` and `CI` strip color.385386CI order: `yapyak translate` with the provider key in the environment, then `yapyak check`, then the build. `check` never calls the translator.387388## Working in a project3893901. Write the `t()` call in the component. With the dev server running, the save writes the stub and the translator fills it. Without it, the CLI finds the call.3912. Run `npx yapyak check` before finishing. Fix every reported `YAPnnnn` with [references/diagnostics.md](references/diagnostics.md).3923. Run `npx yapyak translate` when `check` reports missing translations and the project has a translator. Fill the stubs by hand when it has none.3934. Commit the locale files with the code. They are the source of truth; `.yapyak/` is a cache.3945. Run `npx yapyak clean` after removing components, and `--write` once the list is right.395396Diagnostics an agent most often triggers:397398| Code | Cause | Fix |399| --- | --- | --- |400| `YAP0002` | Template literal source | `t('Hi {name}', { name })` |401| `YAP0004`, `YAP0005`, `YAP0049` | Params do not match the placeholders | Match the keys to the `{names}` in the source |402| `YAP0006` | Params in a variable | Inline object literal |403| `YAP0008` | No `other` branch | Add `other {...}` |404| `YAP0018` | `t()` and `t.as()` for one source in one file | `t.as()` on every occurrence |405| `YAP0020` | Chain stored in a variable | Complete `t.in()` or `t.as()` inline |406| `YAP0046` | Branch name is not a CLDR keyword | `zero`, `one`, `two`, `few`, `many`, `other`, or `=N` |407| `YAP0055` | `t()` at module scope | Move the call into the function that renders it |408| `YAP0022` | `getLocale()` on the server without an adapter | Register the SSR adapter from the framework reference |