autoglot 0.4.3 → 0.6.0
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/README.md +272 -34
- package/bin/add.mjs +42 -6
- package/bin/catalogs.mjs +207 -0
- package/bin/cli.mjs +29 -1
- package/bin/config.mjs +43 -7
- package/bin/doctor.mjs +101 -16
- package/bin/extract.mjs +5 -1
- package/bin/formats/arb.mjs +176 -0
- package/bin/formats/index.mjs +78 -0
- package/bin/formats/json.mjs +15 -0
- package/bin/formats/properties.mjs +127 -0
- package/bin/formats/shared.mjs +22 -0
- package/bin/formats/yaml.mjs +660 -0
- package/bin/helpers.mjs +240 -16
- package/bin/init.mjs +133 -14
- package/bin/providers/anthropic.mjs +51 -0
- package/bin/providers/gemini.mjs +84 -0
- package/bin/providers/index.mjs +387 -0
- package/bin/providers/openai-responses.mjs +73 -0
- package/bin/providers/openai.mjs +74 -0
- package/bin/providers/shared.mjs +148 -0
- package/bin/templates/common.mjs +36 -9
- package/bin/translate.mjs +445 -129
- package/package.json +9 -3
package/README.md
CHANGED
|
@@ -16,15 +16,16 @@
|
|
|
16
16
|
<p align="center">
|
|
17
17
|
<a href="#quickstart">Quickstart</a> ·
|
|
18
18
|
<a href="#how-it-works">How it works</a> ·
|
|
19
|
+
<a href="#providers">Providers</a> ·
|
|
19
20
|
<a href="#configuration">Configuration</a> ·
|
|
20
21
|
<a href="#cli-flags">CLI reference</a>
|
|
21
22
|
</p>
|
|
22
23
|
|
|
23
|
-
autoglot translates
|
|
24
|
+
autoglot translates message catalogs (JSON, Flutter ARB, YAML, Java `.properties`; see [File formats](#file-formats)) with Claude by default, or with OpenAI, Gemini, a local model, or [another provider](#providers). Edit your source locale, then run the CLI or let the GitHub Action commit the updated translations to your branch. Your runtime library, such as [next-intl](https://next-intl.dev/), [react-i18next](https://react.i18next.com/), or [Vue I18n](https://vue-i18n.intlify.dev/), reads the resulting files.
|
|
24
25
|
|
|
25
26
|
- **Incremental.** A committed lock file tracks source strings. autoglot translates new, changed, and missing keys and removes orphaned entries.
|
|
26
|
-
- **Runs where you work.** Use Node.js 20+ locally or in CI. The CLI has zero runtime dependencies and sends translation requests to
|
|
27
|
-
- **Reviewable.** The GitHub Action commits
|
|
27
|
+
- **Runs where you work.** Use Node.js 20+ locally or in CI. The CLI has zero runtime dependencies and sends translation requests to the AI provider you choose, with your own API key.
|
|
28
|
+
- **Reviewable.** The GitHub Action commits the translated catalog files and can post token usage and estimated cost on an open PR.
|
|
28
29
|
|
|
29
30
|
## Quickstart
|
|
30
31
|
|
|
@@ -35,8 +36,8 @@ With Node.js 20 or newer, create an empty directory and preview German translati
|
|
|
35
36
|
```bash
|
|
36
37
|
mkdir autoglot-demo
|
|
37
38
|
cd autoglot-demo
|
|
38
|
-
npx --yes autoglot@0.
|
|
39
|
-
npx --yes autoglot@0.
|
|
39
|
+
npx --yes autoglot@0.6.0 init --locales=de
|
|
40
|
+
npx --yes autoglot@0.6.0 --dry-run
|
|
40
41
|
```
|
|
41
42
|
|
|
42
43
|
`init` creates the English and German JSON catalogs and `translate.config.json`. It also generates a GitHub workflow file that you can ignore for local use. The dry run exits with status `0` and includes these lines for the fresh starter catalog.
|
|
@@ -49,7 +50,7 @@ npx --yes autoglot@0.4.3 --dry-run
|
|
|
49
50
|
To check whether translations are up to date, run this separately.
|
|
50
51
|
|
|
51
52
|
```bash
|
|
52
|
-
npx --yes autoglot@0.
|
|
53
|
+
npx --yes autoglot@0.6.0 --check
|
|
53
54
|
```
|
|
54
55
|
|
|
55
56
|
On this fresh catalog, the check prints `Locales needing updates: de` and exits with status `1` because the German translations are pending. Both commands leave the catalogs and lock file untouched.
|
|
@@ -59,16 +60,18 @@ On this fresh catalog, the check prints `Locales needing updates: de` and exits
|
|
|
59
60
|
When you're ready to translate, edit `messages/en.json`, set `ANTHROPIC_API_KEY` in your environment, and run the CLI without a preview flag. This sends requests to Anthropic and can incur API charges.
|
|
60
61
|
|
|
61
62
|
```bash
|
|
62
|
-
npx --yes autoglot@0.
|
|
63
|
+
npx --yes autoglot@0.6.0
|
|
63
64
|
```
|
|
64
65
|
|
|
66
|
+
To translate with a different provider, see [Providers](#providers).
|
|
67
|
+
|
|
65
68
|
For a dry run with existing catalogs, see the [basic example](https://github.com/ffcabbar/autoglot/tree/main/examples/basic).
|
|
66
69
|
|
|
67
70
|
### Set up an existing app
|
|
68
71
|
|
|
69
|
-
Run `npx autoglot init` in your app directory and choose your target locales. To set them without prompts, use `npx --yes autoglot@0.
|
|
72
|
+
Run `npx autoglot init` in your app directory and choose your target locales. To set them without prompts, use `npx --yes autoglot@0.6.0 init --locales=de,pt-BR`. Setup creates missing files and skips existing paths. Add `--install` to install the suggested runtime libraries. If that install fails, unattended setup exits with an error after printing the retry command.
|
|
70
73
|
|
|
71
|
-
For GitHub automation, add `ANTHROPIC_API_KEY` to your repository secrets before pushing changes to the source catalog.
|
|
74
|
+
For GitHub automation, add `ANTHROPIC_API_KEY` to your repository secrets before pushing changes to the source catalog. To scaffold for another provider, pass `--provider=<name>`; setup then writes that provider to the config, uses its secret name in the workflow, and prints which secret to add. For a provider that runs on your machine, such as `ollama`, setup skips the GitHub workflow, because a GitHub runner cannot reach it.
|
|
72
75
|
|
|
73
76
|
### Supported frameworks
|
|
74
77
|
|
|
@@ -101,7 +104,7 @@ gh secret set ANTHROPIC_API_KEY
|
|
|
101
104
|
npx autoglot # run translation (the default; same as before)
|
|
102
105
|
npx autoglot init # interactive scaffold (above)
|
|
103
106
|
npx autoglot init --install # …and auto-install runtime libs (--pm=pnpm to override)
|
|
104
|
-
npx autoglot add tr ja zh # add new target locales (creates empty
|
|
107
|
+
npx autoglot add tr ja zh # add new target locales (creates empty catalog files)
|
|
105
108
|
npx autoglot doctor # health check the setup
|
|
106
109
|
npx autoglot extract # scan source for hardcoded strings and suggest keys
|
|
107
110
|
npx autoglot extract --write # …and merge them into messages/en.json (existing keys protected)
|
|
@@ -177,21 +180,127 @@ jobs:
|
|
|
177
180
|
|
|
178
181
|
The action detects pull_request events automatically and pushes translations to the PR's source branch. If you forget the `ref:` line, autoglot prints an error explaining how to fix it instead of silently doing the wrong thing.
|
|
179
182
|
|
|
183
|
+
### Action inputs
|
|
184
|
+
|
|
185
|
+
| Input | Default | What it does |
|
|
186
|
+
|---|---|---|
|
|
187
|
+
| `anthropic-api-key` | | Anthropic API key. Needed when the provider is `anthropic`. |
|
|
188
|
+
| `api-key` | | Unbound key for a gateway or an `openai-compatible` endpoint. It is sent to whatever `base-url` / `baseUrl` is configured. For a vendor at its own endpoint, use step `env:` with the vendor variable instead (see below). |
|
|
189
|
+
| `provider` | `anthropic` | One of the [providers](#providers). Falls back to `provider` in the config. Providers other than `anthropic` are verified against simulated responses only. |
|
|
190
|
+
| `model` | `claude-haiku-4-5` for Anthropic | Model id. Every other provider needs one, here or in the config. |
|
|
191
|
+
| `base-url` | the provider's endpoint | API base URL. Needed for `openai-compatible`. |
|
|
192
|
+
| `config` | `translate.config.json` | Path to the config file. |
|
|
193
|
+
| `source`, `messages-dir`, `files`, `lock-file` | from the config | Path overrides. `files` is a catalog path pattern with one `[locale]` in the file name and replaces `messages-dir`. |
|
|
194
|
+
| `commit` | `true` | Commit and push translation changes to the branch. |
|
|
195
|
+
| `pr-comment` | `true` | Post the cost summary on the open PR. |
|
|
196
|
+
| `package-version` | bundled CLI | Run a specific npm version of the CLI. |
|
|
197
|
+
|
|
198
|
+
Existing workflows that pass `anthropic-api-key` keep working unchanged. For another vendor, pass its key as step `env:` under the vendor's own variable name. `autoglot init --provider=<name>` generates this.
|
|
199
|
+
|
|
200
|
+
```yaml
|
|
201
|
+
- uses: ffcabbar/autoglot@v1
|
|
202
|
+
env:
|
|
203
|
+
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
|
204
|
+
with:
|
|
205
|
+
provider: openai
|
|
206
|
+
model: <model-id>
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
A vendor variable (and `anthropic-api-key`, which fills `ANTHROPIC_API_KEY`) is only ever sent to that vendor's own host, so a `baseUrl` added to `translate.config.json` cannot redirect it. Use the `api-key` input only when you mean to send a key to a gateway or an `openai-compatible` endpoint. That key is unbound: it goes to whatever base URL is configured, so review changes to `baseUrl` as carefully as changes to the workflow.
|
|
210
|
+
|
|
211
|
+
```yaml
|
|
212
|
+
- uses: ffcabbar/autoglot@v1
|
|
213
|
+
with:
|
|
214
|
+
provider: openai-compatible
|
|
215
|
+
base-url: https://<your-gateway>/v1
|
|
216
|
+
model: <model-id>
|
|
217
|
+
api-key: ${{ secrets.AUTOGLOT_API_KEY }}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
If the selected provider needs a key and none is passed, the run stops with an error that names the missing variable before any request is sent.
|
|
221
|
+
|
|
180
222
|
## vs. the alternatives
|
|
181
223
|
|
|
182
224
|
| | **autoglot** | Languine | Lokalise / Crowdin / Phrase | i18n-ai-translate |
|
|
183
225
|
|---|:---:|:---:|:---:|:---:|
|
|
184
|
-
| License | **MIT** |
|
|
185
|
-
|
|
|
186
|
-
|
|
|
187
|
-
|
|
|
226
|
+
| License | **MIT** | MIT | Proprietary | MIT |
|
|
227
|
+
| Accounts needed | Model provider | Vercel (hosting, database, AI Gateway) | Vendor account | Model provider (none with local Ollama) |
|
|
228
|
+
| Server to deploy | **None** | Your own Vercel app + Postgres | n/a (vendor-hosted) | None |
|
|
229
|
+
| Dashboard | None | On your deployment | Vendor-hosted (required) | None |
|
|
230
|
+
| GitHub Action | **Yes (built-in)** | Yes (calls your deployment) | Plugin | No |
|
|
188
231
|
| Bot commits the diff back | **Yes** | Yes | Manual | No |
|
|
189
|
-
| Cost
|
|
190
|
-
| Dependencies | **0** |
|
|
191
|
-
| Multi-provider |
|
|
192
|
-
| Formats | JSON | 15+ | 15+ | JSON |
|
|
232
|
+
| Cost | Model usage at provider rates | Model usage via Vercel AI Gateway, plus hosting | $5–$50 per ~1k-key PR | Model usage at provider rates |
|
|
233
|
+
| Dependencies | **0** | 30 (CLI) | n/a (SaaS) | several |
|
|
234
|
+
| Multi-provider | **Yes** (Anthropic run live; others simulated-only) | One model, any Vercel AI Gateway provider | n/a | Yes |
|
|
235
|
+
| Formats | JSON, ARB, YAML, `.properties` | 15+ | 15+ | JSON |
|
|
193
236
|
| Self-hosted | **Yes** | Yes | No | Yes |
|
|
194
237
|
|
|
238
|
+
[Languine](https://github.com/languine-ai/languine) v4 is MIT-licensed and self-hosted: you deploy its web app to your own Vercel account with a Postgres database, then point its CLI and Action at that deployment. It reads many more file formats than autoglot. autoglot has no deployment, database, or login: one `npx` command and your own provider key.
|
|
239
|
+
|
|
240
|
+
## Providers
|
|
241
|
+
|
|
242
|
+
Anthropic is the default, and nothing changes for existing projects. To use another provider, set a provider, a model, and that provider's API key. Catalogs, the lock file, checks, and the Action work the same way with every provider.
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
export OPENAI_API_KEY=... # your own key, read from the environment
|
|
246
|
+
npx autoglot --provider=openai --model=<model-id>
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
Or keep the choice in `translate.config.json`.
|
|
250
|
+
|
|
251
|
+
```json
|
|
252
|
+
{
|
|
253
|
+
"provider": "openai",
|
|
254
|
+
"model": "<model-id>"
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
> **Status.** Only `anthropic` has been run against its live API. Every other provider in this table is verified against simulated responses written from the vendor's documentation, and has not yet been run against the live API. Start with `--dry-run`, then try one small locale with `--locales=<code>` before a full run.
|
|
259
|
+
|
|
260
|
+
| Provider | API key variable | Example | Status | Notes |
|
|
261
|
+
|---|---|---|---|---|
|
|
262
|
+
| `anthropic` *(default)* | `ANTHROPIC_API_KEY` | `--model=claude-haiku-4-5` | Live | Default model `claude-haiku-4-5`. |
|
|
263
|
+
| `openai` | `OPENAI_API_KEY` | `--provider=openai --model=<model-id>` | Simulated only | Responses API, with `store: false` (see the note below). |
|
|
264
|
+
| `gemini` | `GEMINI_API_KEY` or `GOOGLE_API_KEY` | `--provider=gemini --model=<model-id>` | Simulated only | `generateContent` API. If both variables are set, `GOOGLE_API_KEY` wins. |
|
|
265
|
+
| `xai` | `XAI_API_KEY` | `--provider=xai --model=<model-id>` | Simulated only | Responses API, with `store: false`. |
|
|
266
|
+
| `deepseek` | `DEEPSEEK_API_KEY` | `--provider=deepseek --model=<model-id>` | Simulated only | Thinking mode is turned off for the request, because it rejects a forced tool call. |
|
|
267
|
+
| `openrouter` | `OPENROUTER_API_KEY` | `--provider=openrouter --model=<vendor/model-id>` | Simulated only | Pick a model that supports tool calling. |
|
|
268
|
+
| `groq` | `GROQ_API_KEY` | `--provider=groq --model=<model-id>` | Simulated only | |
|
|
269
|
+
| `mistral` | `MISTRAL_API_KEY` | `--provider=mistral --model=<model-id>` | Simulated only | |
|
|
270
|
+
| `together` | `TOGETHER_API_KEY` | `--provider=together --model=<model-id>` | Simulated only | |
|
|
271
|
+
| `ollama` | none | `--provider=ollama --model=<local-model>` | Simulated only | Local server at `http://localhost:11434/v1`. No key. |
|
|
272
|
+
| `openai-compatible` | `AUTOGLOT_API_KEY` (optional) | `--provider=openai-compatible --base-url=<url> --model=<model-id>` | Simulated only | Any endpoint that speaks the OpenAI Chat Completions format. |
|
|
273
|
+
|
|
274
|
+
Use the model ids from your provider's own documentation. Only Anthropic has a default model; every other provider needs `--model` or `"model"` in the config, and autoglot says so if it is missing.
|
|
275
|
+
|
|
276
|
+
**Other vendors and local servers.** `openai-compatible` is for any service that documents an OpenAI-compatible Chat Completions endpoint with tool calling, for example LM Studio's local server at `http://localhost:1234/v1`. If your vendor documents one (Alibaba Qwen on DashScope, Moonshot Kimi, Zhipu GLM, a vLLM server, and so on), take the base URL from its documentation and pass it with `--base-url` or `"baseUrl"`. None of these has been tried, and autoglot ships no preset for them.
|
|
277
|
+
|
|
278
|
+
**Base URLs.**
|
|
279
|
+
|
|
280
|
+
- Give the API base, not the full endpoint: `https://api.example.com/v1`, not `https://api.example.com/v1/chat/completions`. autoglot adds the path and rejects a pasted endpoint, a query string, a fragment, or a URL with a username or password.
|
|
281
|
+
- For `anthropic`, the base is the API root. `https://gateway.example` and `https://gateway.example/v1` both send to `/v1/messages`.
|
|
282
|
+
- A `baseUrl` belongs to the provider it was written for. If the config sets `provider` and `baseUrl` and you pick a different provider with `--provider`, the config's `baseUrl` and `model` are ignored (with a warning for the URL), and you pass `--model` yourself. The same holds for `AUTOGLOT_BASE_URL` and `AUTOGLOT_MODEL` against a provider set in the config.
|
|
283
|
+
- Whenever requests go anywhere other than the provider's own endpoint, the run prints an `Endpoint:` line and adds it to the summary.
|
|
284
|
+
- Redirects are not followed.
|
|
285
|
+
|
|
286
|
+
**API keys.**
|
|
287
|
+
|
|
288
|
+
- Keys are read from environment variables only. autoglot refuses to run if `translate.config.json` contains an `apiKey` field, and there is no key flag.
|
|
289
|
+
- `AUTOGLOT_API_KEY` works for every provider and wins over the provider's own variable.
|
|
290
|
+
- A vendor variable such as `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` is used only for that vendor's own host. **To route any provider through a gateway or proxy, set `AUTOGLOT_API_KEY`** (Action input `api-key`). With a custom base URL and only the vendor variable set, the run stops before any request and names the host. This keeps an edited `baseUrl` from carrying a vendor key to another server.
|
|
291
|
+
- `openai-compatible` and `ollama` read only `AUTOGLOT_API_KEY`.
|
|
292
|
+
- `AUTOGLOT_API_KEY` is sent to whatever base URL is configured. Review changes to `baseUrl` in `translate.config.json` as you would review a change to a workflow.
|
|
293
|
+
- A key is not sent over plain `http` to another machine. Use `https`, or set `"allowInsecureHttp": true` (or `--allow-insecure-http`) if you accept the risk. `http://localhost` is allowed.
|
|
294
|
+
- Your source strings are sent to the provider you select. Check that provider's data-handling terms. For OpenAI and xAI, `store: false` only turns off the stored response object that could be fetched or continued later; it does not change the provider's own retention, such as abuse monitoring.
|
|
295
|
+
|
|
296
|
+
**Structured output is required.** Every provider is asked for a forced tool or function call and autoglot reads only that call. If a model answers in prose, returns arguments that are not valid JSON, omits a key, or returns an empty string for real text (unless `allowEmptyTranslations` is set), autoglot retries once and then fails without writing that locale. If a reply is cut off at the output limit, or the provider refuses, blocks, or reports an error inside the reply, the run fails at once without a second request. One exception: a Gemini reply marked `MALFORMED_FUNCTION_CALL` is retried once like any other malformed call. Ollama's OpenAI-compatible endpoint does not support forcing a tool call, so a local model has to choose the tool by itself; use a model with reliable tool calling. Local models often have small context windows, so lower `chunkSize` (for example `"chunkSize": 25`) if replies are cut off or keys go missing.
|
|
297
|
+
|
|
298
|
+
**Rate limits.** A `429` is retried up to five times. For Anthropic the wait is the `retry-after` seconds, or 60 when the header is missing, exactly as before. For other providers `retry-after` may be seconds or a date, and each wait is kept between 0 and 120 seconds. A `429` that reports exhausted quota or credit is not retried.
|
|
299
|
+
|
|
300
|
+
**Request parameters.** Anthropic requests keep `max_tokens: 8192` and `temperature: 0`. For other providers autoglot sends no output limit unless you set `maxOutputTokens`, because reasoning models count their thinking against it. `temperature: 0` is sent where the provider documents it and left out for OpenAI; set `"temperature"` in the config to a number to send one, or to `null` to leave it out.
|
|
301
|
+
|
|
302
|
+
See [`examples/providers`](https://github.com/ffcabbar/autoglot/tree/main/examples/providers) for a keyless dry run with a non-default provider.
|
|
303
|
+
|
|
195
304
|
## Configuration
|
|
196
305
|
|
|
197
306
|
`translate.config.json` (optional — sensible defaults):
|
|
@@ -215,14 +324,114 @@ The action detects pull_request events automatically and pushes translations to
|
|
|
215
324
|
|
|
216
325
|
| Field | Default | What it does |
|
|
217
326
|
|---|---|---|
|
|
218
|
-
| `source` | `messages/en.json` | Path to your source-of-truth locale file. |
|
|
327
|
+
| `source` | `messages/en.json` | Path to your source-of-truth locale file. Its extension picks the [file format](#file-formats). |
|
|
219
328
|
| `messagesDir` | `messages` | Where the other `<locale>.json` files live. |
|
|
329
|
+
| `files` | none | Catalog path pattern with one `[locale]` in the file name, such as `lib/l10n/app_[locale].arb`. Replaces `messagesDir`. See [File formats](#file-formats). |
|
|
330
|
+
| `locales` | none | The exact list of target locales, such as `["de", "fr", "pt-BR"]`. Without it, target files are found by name. See [File names](#file-names). |
|
|
220
331
|
| `lockFile` | `translate.lock` | Where to store md5 fingerprints. Commit it. |
|
|
221
|
-
| `
|
|
332
|
+
| `provider` | `anthropic` | Which [provider](#providers) translates. |
|
|
333
|
+
| `model` | `claude-haiku-4-5` | Model id. The default applies to Anthropic only; other providers need one. |
|
|
334
|
+
| `baseUrl` | the provider's endpoint | API base URL. Required for `openai-compatible`. |
|
|
335
|
+
| `pricing` | built-in for listed Claude models | `{ "input": 1.0, "output": 5.0 }` in USD per 1M tokens. Enables cost reporting for any model. |
|
|
336
|
+
| `chunkSize` | `200` | Keys sent per request. Lower it if a reply is cut off. |
|
|
337
|
+
| `maxOutputTokens` | `8192` for Anthropic, provider default otherwise | Output token limit per request. |
|
|
338
|
+
| `temperature` | per provider | A number to send, or `null` to leave it out of the request. |
|
|
339
|
+
| `allowInsecureHttp` | `false` | Allow sending an API key over plain `http` to a host other than this machine. |
|
|
340
|
+
| `allowEmptyTranslations` | `false` | Accept an empty string as the translation of non-empty source text. By default that is retried once and then rejected. |
|
|
222
341
|
| `glossary` | `[]` | Product/brand names the model must keep verbatim. |
|
|
223
342
|
| `namespaceContext` | `{}` | Hint the model about each top-level namespace. Improves quality. |
|
|
224
343
|
| `namespaces` | `{}` | Map namespaces to their target locale lists. Other namespaces go to all target locales. |
|
|
225
344
|
|
|
345
|
+
## File formats
|
|
346
|
+
|
|
347
|
+
The format is chosen from the extension of the source file. Target files use the same extension. A source file with any other extension, or none, is read as JSON, as in earlier versions; a `files` pattern with an unsupported extension is an error.
|
|
348
|
+
|
|
349
|
+
| Format | Extensions | What is translated | What a target file keeps | Limits |
|
|
350
|
+
|---|---|---|---|---|
|
|
351
|
+
| JSON | `.json` | Every value of a nested object | Source key order | Unchanged from earlier versions. |
|
|
352
|
+
| ARB (Flutter) | `.arb` | Every key that does not start with `@` | `@@locale` set to the target's own locale; the target's own other `@@` entries, and its `@key` entries for messages that still exist | Message values must be strings. The source's `@key` entries (descriptions, placeholders) are not copied: Flutter reads them from the template file. A key that is a whole number (`"404"`) is written before the other keys. |
|
|
353
|
+
| YAML (Rails, i18next) | `.yaml`, `.yml` | String values of nested mappings; lists of strings, item by item | Source structure, key order and key spelling; the Rails locale root, rewritten to the target locale; values that are not text | A documented subset, see below. Comments are not copied. |
|
|
354
|
+
| Java properties | `.properties` | Every value | Source key order | Read and written as UTF-8. Comments are not copied. |
|
|
355
|
+
|
|
356
|
+
Not supported: gettext PO, Apple `.strings` / `.stringsdict` / `.xcstrings`, Android XML, XLIFF, Markdown. One directory per locale (`locales/de/common.json`, `values-de/strings.xml`) is not supported yet either: catalogs are one file per locale in one directory.
|
|
357
|
+
|
|
358
|
+
Rules that hold for every format:
|
|
359
|
+
|
|
360
|
+
- `translate.lock` is the same for all of them: one md5 per dotted key. A JSON project's lock file does not change.
|
|
361
|
+
- A source file that cannot be read stops the run before anything is sent or written.
|
|
362
|
+
- A target file that cannot be read is reported with its file and line, left untouched and kept pending. The other locales are still translated, and the run exits with status `1`.
|
|
363
|
+
- Every ARB, YAML and `.properties` file is checked before it is written: it must read back as exactly the translations it was made from, whatever characters a translation contains. JSON files are written as before, without this check.
|
|
364
|
+
- **First run on a project that already has translations.** `translate.lock` is what tells autoglot that a translation is current. Without a lock file, the first run translates every key again and overwrites the translations already in the target files, and it removes keys that only a target has. This is how JSON projects have always behaved. Commit your target files before the first run and review the diff.
|
|
365
|
+
- A key that exists only in a target file is removed on the next write (with one exception for Rails plural forms, below), and comments in target files are not kept.
|
|
366
|
+
- Target files are written with LF line endings. Source files may use LF or CRLF.
|
|
367
|
+
- Files other than JSON must be valid UTF-8.
|
|
368
|
+
|
|
369
|
+
### File names
|
|
370
|
+
|
|
371
|
+
By default a catalog is `<messagesDir>/<locale>` plus the source file's extension, so a Rails project needs no extra setting:
|
|
372
|
+
|
|
373
|
+
```json
|
|
374
|
+
{ "source": "config/locales/en.yml", "messagesDir": "config/locales" }
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
When the file name holds more than the locale, give the pattern in `files` (or `--files=`, or the Action's `files` input) instead of `messagesDir`:
|
|
378
|
+
|
|
379
|
+
```json
|
|
380
|
+
{ "files": "lib/l10n/app_[locale].arb" }
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
```json
|
|
384
|
+
{ "source": "src/main/resources/messages.properties", "files": "src/main/resources/messages_[locale].properties" }
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
- `[locale]` must appear exactly once, in the file name. A pattern with `[locale]` in a directory name is refused.
|
|
388
|
+
- Without `source`, the source file is the pattern with `en` as the locale. Set `source` when it is another file, for example Java's `messages.properties`.
|
|
389
|
+
- `files` together with a `messagesDir` that names another directory, or a `source` with another extension, is an error. autoglot never picks one of two contradicting settings.
|
|
390
|
+
|
|
391
|
+
Which files are targets:
|
|
392
|
+
|
|
393
|
+
- **JSON projects without `files`:** every `*.json` in `messagesDir` except the source, as before.
|
|
394
|
+
- **Every other project** (ARB, YAML, `.properties`, or any project that sets `files`): a file is a target only if the locale part of its name is a known language code, optionally followed by a known script and a known region: `de`, `pt-BR`, `pt_BR`, `zh-Hans`, `zh_Hant_TW`. `models.yml`, `faq.yml`, `app_config.yml`, `devise.en.yml` or `messages_dev.properties` next to your catalogs are not targets and are never written.
|
|
395
|
+
- Some ordinary words are also language codes (`nav`, `bak`, `new`). So a file found by name that already has content and no history in `translate.lock` is a target only if at least half of its own keys are keys of the source catalog (a real translation is a subset of the source, apart from a few stale keys). Every value counts as content, including numbers and flags. Otherwise the file is skipped with a warning and never written or staged; the run lists the skipped files in its summary and still exits with status `0`, `--check` does not count them as pending, and `autoglot doctor` names them. An empty file is always a target.
|
|
396
|
+
- **`"locales"` in the config** replaces all of this with an exact list: `"locales": ["de", "fr", "pt-BR"]`. Only the listed locales are targets, in every format including JSON; a listed locale without a file gets one on the next run; no other file is read or written. Use it to include a file the rules above skip, or to keep autoglot away from everything else in the directory. `--locales=` selects from the list and refuses a locale that is not on it. A list with no target locale in it is an error; the source locale in the list is ignored with a warning.
|
|
397
|
+
- Outside the JSON default layout, `pt-BR`, `pt_BR` and `PT-br` name the same catalog in `--locales`, in `"locales"`, and in `add` and `init`: the file that exists is used, and a new file gets the spelling and letter case of its ecosystem (`add fr-ca` creates `app_fr_CA.arb`). Two files for one locale (`app_pt_BR.arb` and `app_pt-BR.arb`) stop the run until one is removed.
|
|
398
|
+
|
|
399
|
+
`autoglot add <locale>` creates an empty target with the right name and shape (`de: {}` for Rails, `"@@locale": "de"` for ARB). `add` and `init` accept both `pt-BR` and `pt_BR` for these formats and write the spelling each ecosystem uses: `app_pt_BR.arb` and `messages_pt_BR.properties` with an underscore, `pt-BR.yml` with a hyphen. `autoglot doctor` prints the detected format and pattern. `autoglot init` scaffolds starter catalogs for JSON only; for another format, write `translate.config.json` by hand, then run `autoglot add <locale>`. Running `init` on such a project adds the empty targets and a workflow that triggers on your catalog files. `--import-languine` and `autoglot extract --write` work with JSON catalogs only.
|
|
400
|
+
|
|
401
|
+
Runnable examples: [`examples/flutter-arb`](https://github.com/ffcabbar/autoglot/tree/main/examples/flutter-arb) and [`examples/rails-yaml`](https://github.com/ffcabbar/autoglot/tree/main/examples/rails-yaml).
|
|
402
|
+
|
|
403
|
+
### ARB
|
|
404
|
+
|
|
405
|
+
Keys that start with `@` are never sent to the model. A target's `@@` entries always stay; its `@key` entry stays as long as the message `key` exists and is removed together with a message that was deleted from the source. A target gets `@@locale` when the source file or the target already has one. ICU messages are checked by argument: a translation of `{count, plural, one{item} other{{count} items}}` must still contain `count` as a plural and `{count}` as a plain argument. Plural and select branch keywords (`one`, `few`, `=0`, `male`) and the text inside branches are not checked, because languages need different plural categories. Text that is not well-formed ICU falls back to the plain `{name}` check. An apostrophe is read both ways, as text (Flutter's default, so `l'{item}` keeps its placeholder) and as ICU quoting (`use-escaping: true`); a translation passes if either reading has the source's arguments.
|
|
406
|
+
|
|
407
|
+
### YAML
|
|
408
|
+
|
|
409
|
+
autoglot reads YAML with its own parser for a strict subset, and stops with the file, line and construct for anything outside it.
|
|
410
|
+
|
|
411
|
+
- Supported: one document (optionally opened with `---`); nested block mappings; plain, single-quoted and double-quoted keys and values, on one line or folded over several, with all double-quote escapes; literal `|` and folded `>` block scalars with `+` / `-` chomping and an indentation digit; lists of scalars written as `- item` lines or as a one-line `[a, b]`; comments; empty values; `{}` and `[]`.
|
|
412
|
+
- Refused: anchors `&`, aliases `*`, tags `!`, merge keys `<<`, complex keys `?`, flow mappings `{a: b}`, lists that contain mappings or lists, `[ ]` lists over several lines, more than one document, `%` directives, tabs used for indentation, duplicate keys, and a few things that YAML readers disagree about (a block scalar on the last line of a file that has no final line break; a raw U+2028, U+2029 or U+0085 character, which Ruby reads as a line break).
|
|
413
|
+
- A list is translated item by item. The items of `day_names` are the lock keys `day_names.0`, `day_names.1`, and so on. This differs from JSON catalogs, where an array is one value with one hash.
|
|
414
|
+
- Values that are not text are never sent and never retyped: numbers and anything shaped like one, `true` / `false`, `null` / `~` / an empty value, dates, and Ruby symbols (a plain value that starts with a colon, like `:year`). A target keeps its own such value if it has one and otherwise gets the source's, character for character.
|
|
415
|
+
- A plain `yes`, `no`, `on`, `off`, `y` or `n` is a boolean for YAML 1.1 readers such as Ruby and a string for YAML 1.2 readers. autoglot refuses it and asks you to quote it.
|
|
416
|
+
- Rails locale root: when the only top-level key of a file is its own locale (`en:` in `en.yml`), the messages are what is under it and each target is written under its own locale (`de:`). The root is not part of the lock keys. A target that is rooted differently from the source is refused instead of being rewritten.
|
|
417
|
+
- Rails plural forms: under a mapping whose source keys are all plural categories (`zero`, `one`, `two`, `few`, `many`, `other`), plural categories that only the target has are kept, after the source's keys. A Russian file keeps the `few` and `many` a translator added. autoglot does not create missing categories: it translates the keys the source has (`one`, `other`), and the extra forms a language needs must be added by hand. Kept forms are also not refreshed: when the source's plural text changes, `one` and `other` are translated again and `few` and `many` stay as they were until someone updates them.
|
|
418
|
+
- A value with an ICU plural or select (`{n, plural, one {file} other {files}}`) is checked by its arguments, as in ARB, so the words in its branches are free.
|
|
419
|
+
- Placeholders are compared as written: `%{name}`, a bare `{name}` and `%<name>d` are different things, and `%<name>d` must keep its conversion letter. Their order, and the width or precision of `%<name>d`, are free. `printf`-style `%s` and `%d` are not checked.
|
|
420
|
+
- Typing that only Ruby's YAML reader applies is not modelled: a mixed-case `tRue`, or a multi-line unquoted value in which one line is exactly `yes`, is text to autoglot.
|
|
421
|
+
- Unicode spaces (a no-break space, an ideographic space) are content, never trimmed. In targets they are written as escapes inside double quotes (`"Prix\_:"`) so they stay visible.
|
|
422
|
+
- Writing: keys are copied exactly as the source spells them. A translated string is written plain only when that is safe for both YAML 1.1 and YAML 1.2 readers; otherwise it is double-quoted with escapes. Block scalars in the source become double-quoted strings in targets.
|
|
423
|
+
|
|
424
|
+
### Java properties
|
|
425
|
+
|
|
426
|
+
Files are read the way `java.util.Properties` reads them: `key=value`, `key:value` and `key value`; `#` and `!` comments; a trailing backslash continuing a line; the escapes `\t`, `\n`, `\r`, `\f`, `\uXXXX` and a backslash before any other character. A key that appears twice keeps its last value. A malformed `\uXXXX` is an error.
|
|
427
|
+
|
|
428
|
+
- Keys are flat. `checkout.title` is one key, dots included, and that is its key in `translate.lock`.
|
|
429
|
+
- Encoding: files are read and written as UTF-8, and text outside ASCII is written as it is. If the source file itself uses `\uXXXX` escapes and contains no character outside ASCII, targets use `\uXXXX` too. Invisible characters (no-break spaces, zero-width characters, the byte order mark) are always written as `\uXXXX`. A file in ISO-8859-1 is refused; convert it to UTF-8 first.
|
|
430
|
+
- A value with an ICU plural or select is checked by its arguments, as in ARB, so the words in its branches are free.
|
|
431
|
+
- Placeholders: numbered arguments (`{0}`, `{1,number}`) and named ones (`{name}`) must appear in the translation with the same format type (`number`, `date`, `choice`); their order and the format style are free. `printf`-style `%s` is not checked, and neither is `MessageFormat` quoting such as `'{0}'`.
|
|
432
|
+
- `MessageFormat` rules such as doubling an apostrophe in a message with arguments are not checked. The model is told to follow the source's convention.
|
|
433
|
+
- The parser follows the `java.util.Properties` specification and was compared with two JavaScript parsers; it has not been run against a Java runtime.
|
|
434
|
+
|
|
226
435
|
## CLI flags
|
|
227
436
|
|
|
228
437
|
```
|
|
@@ -230,9 +439,16 @@ The action detects pull_request events automatically and pushes translations to
|
|
|
230
439
|
--dry-run Preview the translation plan without updating catalogs.
|
|
231
440
|
--quiet Suppress per-locale and per-chunk progress. CI keeps verbose logs.
|
|
232
441
|
--locales=de,fr Restrict run to specific locales.
|
|
442
|
+
--provider=<name> Pick the AI provider (default: anthropic).
|
|
233
443
|
--model=<id> Override the configured model.
|
|
444
|
+
--base-url=<url> Override the provider's API base URL.
|
|
445
|
+
--chunk-size=<n> Keys per request (default: 200).
|
|
446
|
+
--max-output-tokens=<n> Output token limit per request.
|
|
447
|
+
--allow-insecure-http Allow sending an API key over plain http to another machine.
|
|
234
448
|
--source=<path> Override config.source.
|
|
235
449
|
--messages-dir=<path> Override config.messagesDir.
|
|
450
|
+
--files=<pattern> Catalog path pattern with one [locale] in the file name, e.g.
|
|
451
|
+
lib/l10n/app_[locale].arb. Replaces --messages-dir.
|
|
236
452
|
--lock-file=<path> Override config.lockFile.
|
|
237
453
|
--config=<path> Custom config file path.
|
|
238
454
|
--import-languine[=path] Seed the lock file from languine.lock.
|
|
@@ -241,6 +457,8 @@ The action detects pull_request events automatically and pushes translations to
|
|
|
241
457
|
-h, --help Print help and exit.
|
|
242
458
|
```
|
|
243
459
|
|
|
460
|
+
Each setting is resolved in this order: CLI flag, then `translate.config.json`, then environment (`AUTOGLOT_PROVIDER`, `AUTOGLOT_MODEL`, `AUTOGLOT_BASE_URL`), then the built-in default. A model or base URL from a lower level is used only if that level was set up for the provider that ends up selected; see [Base URLs](#providers).
|
|
461
|
+
|
|
244
462
|
Use `--locales=es` to translate only Spanish. Later runs reuse that work if the source string is still the same and the translation is present. After an English edit in a project with Spanish and German catalogs, running `--locales=es` and then running without the flag sends the changed string once for Spanish and once for German. Existing v1 lock files work as-is. Keep the updated lock file with the catalogs so later runs can reuse the recorded progress.
|
|
245
463
|
|
|
246
464
|
On case-insensitive filesystems, `pt-br` refers to an existing `pt-BR.json` in both `--locales` and `namespaces` locale lists. A case-only rename carries the catalog's recorded progress to the new filename. If your filesystem has distinct catalogs that differ only in case, use the exact locale spelling from the filename.
|
|
@@ -259,6 +477,18 @@ After a fatal locale error, Autoglot stops starting queued locales and lets acti
|
|
|
259
477
|
|
|
260
478
|
Cost depends on the catalog, target locales, and token usage. See [Anthropic’s pricing](https://platform.claude.com/docs/en/about-claude/pricing) for current rates.
|
|
261
479
|
|
|
480
|
+
Any model id is accepted, for every provider. autoglot has built-in prices for the three models above. For any other model, including every non-Anthropic one, the run reports token counts and shows the cost as `n/a`. To get a cost estimate, add the rates from your provider's pricing page to the config.
|
|
481
|
+
|
|
482
|
+
```json
|
|
483
|
+
{
|
|
484
|
+
"provider": "openai",
|
|
485
|
+
"model": "<model-id>",
|
|
486
|
+
"pricing": { "input": 1.0, "output": 5.0 }
|
|
487
|
+
}
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
`pricing` is in USD per 1M tokens. It also overrides the built-in price of a listed model. The estimate uses the input and output token counts the provider reports and does not account for cache or batch discounts.
|
|
491
|
+
|
|
262
492
|
## Migrating from Languine
|
|
263
493
|
|
|
264
494
|
```bash
|
|
@@ -266,7 +496,9 @@ npx autoglot --import-languine=languine.lock
|
|
|
266
496
|
npx autoglot --dry-run
|
|
267
497
|
```
|
|
268
498
|
|
|
269
|
-
|
|
499
|
+
`languine.lock` sits next to `languine.json`. The importer reads the entry for your source JSON catalog and ignores entries for other files.
|
|
500
|
+
|
|
501
|
+
Keep your existing locale files and review the dry-run output before replacing the Languine workflow: it prints how many keys each locale would get. To see key names, run `npx autoglot --check`, which lists the new or changed source keys and the locales that need updates, and exits with status `1` while anything is pending. The import prints the entries it did not carry over. Any key it could not match to your source catalog appears as new and is re-translated, and array values are re-translated on the first run because Languine hashes each array item while autoglot hashes the whole array as one value.
|
|
270
502
|
|
|
271
503
|
## How it works
|
|
272
504
|
|
|
@@ -276,7 +508,7 @@ Keep your existing locale files and review the dry-run output before replacing t
|
|
|
276
508
|
|
|
277
509
|
1. **Flatten** your source JSON to dotted keys: `{ "checkout.cta": "Pay now" }`.
|
|
278
510
|
2. **Diff** each value's md5 against the lock file. The shared hashes track progress across all applicable locales, and optional per-locale hashes record progress when locales differ.
|
|
279
|
-
3. **For each locale**: collect missing + changed keys, chunk into batches of 200, call
|
|
511
|
+
3. **For each locale**: collect missing + changed keys, chunk into batches of 200, call the provider with a forced tool call (Anthropic [tool use](https://docs.anthropic.com/en/docs/build-with-claude/tool-use), or function calling elsewhere) so the response is structured JSON (not freeform).
|
|
280
512
|
4. **Validate** placeholders (`{name}`) match between source and translation; retry on mismatch.
|
|
281
513
|
5. **Merge** translations back into the locale's JSON, preserving source key order, dropping orphan keys.
|
|
282
514
|
6. **Update** the lock file, write a markdown summary, exit.
|
|
@@ -295,21 +527,21 @@ Yes. `npx autoglot init` has explicit support for **Next.js (App Router & Pages
|
|
|
295
527
|
<details>
|
|
296
528
|
<summary><strong>What about ICU plurals, dates, gender?</strong></summary>
|
|
297
529
|
|
|
298
|
-
ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt to
|
|
530
|
+
ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt sent to the model. The placeholder validator covers `{name}` tokens; ICU structure is handled by the model and should be reviewed in the resulting JSON. For ARB files the validator also checks ICU arguments by name and kind (see [ARB](#arb)), and YAML and `.properties` values that hold an ICU plural or select are read the same way. JSON catalogs keep the plain check, which has a known limit: a plural or select branch that is a single word in braces, as in `one {file} other {files}`, is taken for a placeholder, so its translation is rejected. Write such branches with more than one word (`one {# file}`), or keep them out of JSON catalogs for now.
|
|
299
531
|
|
|
300
532
|
</details>
|
|
301
533
|
|
|
302
534
|
<details>
|
|
303
|
-
<summary><strong>
|
|
535
|
+
<summary><strong>Which file formats are supported?</strong></summary>
|
|
304
536
|
|
|
305
|
-
JSON
|
|
537
|
+
JSON, Flutter ARB, YAML (Rails and i18next style) and Java `.properties`, one file per locale. See [File formats](#file-formats) for what each one translates and keeps, and for the YAML subset. PO, Apple `.strings` / `.xcstrings`, Android XML and one-directory-per-locale layouts are not supported yet.
|
|
306
538
|
|
|
307
539
|
</details>
|
|
308
540
|
|
|
309
541
|
<details>
|
|
310
|
-
<summary><strong>
|
|
542
|
+
<summary><strong>Can I use OpenAI, Gemini, Grok, DeepSeek, or a local model?</strong></summary>
|
|
311
543
|
|
|
312
|
-
|
|
544
|
+
Yes. Anthropic is the default, and `--provider` selects OpenAI, Gemini, xAI, DeepSeek, OpenRouter, Groq, Mistral, Together AI, Ollama, or any OpenAI-compatible endpoint. You bring the key and the model id. These providers are verified against simulated responses only and have not yet been run against the live APIs. See [Providers](#providers).
|
|
313
545
|
|
|
314
546
|
</details>
|
|
315
547
|
|
|
@@ -330,16 +562,20 @@ Yes. `npx autoglot` works in any CI (GitLab, CircleCI, Jenkins, your laptop). Th
|
|
|
330
562
|
<details>
|
|
331
563
|
<summary><strong>How do I keep brand names from being translated?</strong></summary>
|
|
332
564
|
|
|
333
|
-
Add them to `glossary` in `translate.config.json`. They'll be passed to
|
|
565
|
+
Add them to `glossary` in `translate.config.json`. They'll be passed to the model with explicit instruction to leave them verbatim.
|
|
334
566
|
|
|
335
567
|
</details>
|
|
336
568
|
|
|
337
569
|
## Roadmap
|
|
338
570
|
|
|
339
|
-
- [x]
|
|
340
|
-
- [
|
|
341
|
-
- [
|
|
342
|
-
- [ ]
|
|
571
|
+
- [x] Anthropic, JSON catalogs, GitHub Action, Languine importer, parallel locales, lock file
|
|
572
|
+
- [x] Multi-provider — OpenAI, Gemini, xAI, DeepSeek, and OpenAI-compatible endpoints (simulated responses only so far)
|
|
573
|
+
- [x] File formats — ARB, YAML and Java `.properties` next to JSON, with a `[locale]` file name pattern
|
|
574
|
+
- [ ] Run each non-Anthropic provider against its live API
|
|
575
|
+
- [ ] Adopt existing translations into the lock without translating them again (in development)
|
|
576
|
+
- [ ] One directory per locale
|
|
577
|
+
- [ ] More formats — PO, `.strings` / `.xcstrings`, Android XML
|
|
578
|
+
- [ ] Provider-fallback chain
|
|
343
579
|
|
|
344
580
|
See the [roadmap](ROADMAP.md) for upcoming work and the [open issues](https://github.com/ffcabbar/autoglot/issues) for current maintenance tasks.
|
|
345
581
|
|
|
@@ -347,7 +583,9 @@ See the [roadmap](ROADMAP.md) for upcoming work and the [open issues](https://gi
|
|
|
347
583
|
|
|
348
584
|
Issues, PRs, and bug reports welcome. The codebase is intentionally tiny:
|
|
349
585
|
|
|
350
|
-
- `bin/translate.mjs` (≈
|
|
586
|
+
- `bin/translate.mjs` (≈ 960 lines) — the translation engine
|
|
587
|
+
- `bin/formats/` — one module per catalog format (JSON, ARB, YAML, `.properties`)
|
|
588
|
+
- `bin/providers/` — one small module per wire format (Anthropic, OpenAI Responses, OpenAI-compatible Chat Completions, Gemini) plus the preset list
|
|
351
589
|
- `bin/helpers.mjs` — pure helpers
|
|
352
590
|
- `tests/helpers.test.mjs` — `node:test` suite, runs offline
|
|
353
591
|
|
|
@@ -360,7 +598,7 @@ cd examples/basic && node ../../bin/cli.mjs --dry-run
|
|
|
360
598
|
|
|
361
599
|
## Sponsor
|
|
362
600
|
|
|
363
|
-
If `autoglot` saves you the cost of a
|
|
601
|
+
If `autoglot` saves you the cost of a translation SaaS subscription, consider [sponsoring on GitHub](https://github.com/sponsors/ffcabbar). The whole project is one person's evenings.
|
|
364
602
|
|
|
365
603
|
## License
|
|
366
604
|
|
package/bin/add.mjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
// `autoglot add <locale> [<locale>...]` — add new target locales.
|
|
2
2
|
//
|
|
3
|
-
// Creates an empty
|
|
4
|
-
//
|
|
3
|
+
// Creates an empty target catalog in the project's format and naming
|
|
4
|
+
// (messages/<locale>.json by default). The next run populates it.
|
|
5
|
+
// Idempotent: if the file already exists, we leave it alone.
|
|
5
6
|
|
|
6
7
|
import { writeFileSync, existsSync } from "node:fs";
|
|
7
8
|
import { join, relative, basename } from "node:path";
|
|
8
9
|
import { info, ok, warn, err, step } from "./prompts.mjs";
|
|
9
10
|
import { resolvePaths, parseSharedFlags } from "./config.mjs";
|
|
11
|
+
import { catalogLayout, isLocaleName } from "./catalogs.mjs";
|
|
12
|
+
import { readCatalog } from "./formats/index.mjs";
|
|
10
13
|
|
|
11
14
|
export async function run(argv = []) {
|
|
12
15
|
const { args, positional } = parseSharedFlags(argv);
|
|
@@ -20,8 +23,10 @@ export async function run(argv = []) {
|
|
|
20
23
|
step("autoglot add");
|
|
21
24
|
|
|
22
25
|
let paths;
|
|
26
|
+
let layout;
|
|
23
27
|
try {
|
|
24
28
|
paths = resolvePaths(args, cwd);
|
|
29
|
+
layout = catalogLayout(paths);
|
|
25
30
|
} catch (e) {
|
|
26
31
|
err(e.message);
|
|
27
32
|
process.exit(1);
|
|
@@ -35,22 +40,53 @@ export async function run(argv = []) {
|
|
|
35
40
|
process.exit(1);
|
|
36
41
|
}
|
|
37
42
|
|
|
43
|
+
// An empty target mirrors the source where the format needs it: the locale
|
|
44
|
+
// root of a Rails YAML file, "@@locale" in ARB. JSON starts as "{}".
|
|
45
|
+
let sourceMeta = null;
|
|
46
|
+
if (!layout.legacyJson) {
|
|
47
|
+
try {
|
|
48
|
+
sourceMeta = readCatalog(layout.format, paths.source, {
|
|
49
|
+
file: relative(cwd, paths.source) || paths.source, locale: layout.sourceLocale,
|
|
50
|
+
}).meta;
|
|
51
|
+
} catch (e) {
|
|
52
|
+
err(e.message);
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
38
57
|
let added = 0;
|
|
39
58
|
let already = 0;
|
|
40
|
-
for (const
|
|
41
|
-
|
|
59
|
+
for (const given of positional) {
|
|
60
|
+
// Other formats also take pt_BR, pt-BR and zh-Hans, and the file gets the
|
|
61
|
+
// spelling the format's tools expect (app_pt_BR.arb, pt-BR.yml).
|
|
62
|
+
let code = given;
|
|
63
|
+
try {
|
|
64
|
+
// An existing app_pt_BR.arb is the catalog for both pt-BR and pt_BR.
|
|
65
|
+
if (/^[^\\/]+$/.test(given)) code = layout.resolveName(given);
|
|
66
|
+
} catch (e) {
|
|
67
|
+
err(e.message);
|
|
68
|
+
process.exit(1);
|
|
69
|
+
}
|
|
70
|
+
if (!(layout.legacyJson ? /^[a-z]{2,3}(-[A-Z]{2})?$/.test(code) : isLocaleName(code) || layout.allowlist?.(code))) {
|
|
42
71
|
warn(`"${code}" doesn't look like an ISO locale code. Skipping.`);
|
|
43
72
|
continue;
|
|
44
73
|
}
|
|
45
|
-
const localePath =
|
|
74
|
+
const localePath = layout.pathFor(code);
|
|
75
|
+
if (localePath.toLowerCase() === paths.source.toLowerCase()) {
|
|
76
|
+
warn(`"${code}" is the source locale. Skipping.`);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
46
79
|
const displayPath = relative(cwd, localePath) || localePath;
|
|
47
80
|
if (existsSync(localePath)) {
|
|
48
81
|
info(`${displayPath} already exists — leaving it alone.`);
|
|
49
82
|
already++;
|
|
50
83
|
continue;
|
|
51
84
|
}
|
|
52
|
-
writeFileSync(localePath,
|
|
85
|
+
writeFileSync(localePath, layout.format.serialize({}, { meta: null, sourceMeta, locale: code }));
|
|
53
86
|
ok(displayPath);
|
|
87
|
+
if (layout.allowlist && !layout.allowlist(code)) {
|
|
88
|
+
warn(`"${code}" is not in "locales" in translate.config.json. Add it there, or autoglot will not translate this file.`);
|
|
89
|
+
}
|
|
54
90
|
added++;
|
|
55
91
|
}
|
|
56
92
|
|