autoglot 0.1.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/LICENSE +21 -0
- package/README.md +312 -0
- package/bin/helpers.mjs +147 -0
- package/bin/translate.mjs +459 -0
- package/package.json +69 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Furkan Cabbar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
<!-- HERO BANNER
|
|
2
|
+
File: .github/assets/hero.png
|
|
3
|
+
Size: 1280x640 (2:1) — also used as GitHub social card (Settings → Social preview)
|
|
4
|
+
Prompt: "A minimal, modern banner for an open-source dev tool called 'autoglot'.
|
|
5
|
+
Centered wordmark in a clean geometric sans-serif (Inter / Geist), with
|
|
6
|
+
a small globe-and-translation glyph to the left. Background: subtle
|
|
7
|
+
purple-to-near-black diagonal gradient (#1a0b2e → #4c1d95). White text.
|
|
8
|
+
Tagline below the wordmark in a smaller weight: 'AI translation bot for
|
|
9
|
+
your i18n JSON. MIT, single-file, your API key.' Flat, no 3D, no AI
|
|
10
|
+
glow effects. Looks at home next to Vercel/Resend/Linear branding."
|
|
11
|
+
-->
|
|
12
|
+
<p align="center">
|
|
13
|
+
<img src=".github/assets/hero.svg" alt="autoglot — AI-powered i18n translation bot" width="820">
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
<h1 align="center">autoglot</h1>
|
|
17
|
+
|
|
18
|
+
<p align="center">
|
|
19
|
+
<strong>AI-powered i18n translation bot.</strong> Edit <code>en.json</code>, push, and your other locale files appear translated in a bot commit.<br>
|
|
20
|
+
MIT alternative to <a href="https://languine.ai">Languine</a>, Lokalise, and Crowdin.
|
|
21
|
+
</p>
|
|
22
|
+
|
|
23
|
+
<p align="center">
|
|
24
|
+
<a href="https://www.npmjs.com/package/autoglot"><img src="https://img.shields.io/npm/v/autoglot.svg?color=8b5cf6&label=npm" alt="npm"></a>
|
|
25
|
+
<a href="https://www.npmjs.com/package/autoglot"><img src="https://img.shields.io/npm/dm/autoglot.svg?color=8b5cf6" alt="downloads"></a>
|
|
26
|
+
<a href="https://github.com/ffcabbar/autoglot/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/autoglot.svg?color=8b5cf6" alt="license MIT"></a>
|
|
27
|
+
<a href="https://github.com/marketplace/actions/autoglot"><img src="https://img.shields.io/badge/marketplace-autoglot-8b5cf6?logo=githubactions&logoColor=white" alt="GitHub Marketplace"></a>
|
|
28
|
+
<a href="https://github.com/ffcabbar/autoglot/stargazers"><img src="https://img.shields.io/github/stars/ffcabbar/autoglot?style=flat&color=8b5cf6" alt="stars"></a>
|
|
29
|
+
<a href="https://github.com/sponsors/ffcabbar"><img src="https://img.shields.io/badge/sponsor-%E2%9D%A4-ec4899" alt="Sponsor"></a>
|
|
30
|
+
</p>
|
|
31
|
+
|
|
32
|
+
<p align="center">
|
|
33
|
+
<a href="#quickstart-github-action">Quickstart</a> ·
|
|
34
|
+
<a href="#how-it-works">How it works</a> ·
|
|
35
|
+
<a href="#vs-the-alternatives">vs. Languine / Lokalise</a> ·
|
|
36
|
+
<a href="#configuration">Config</a> ·
|
|
37
|
+
<a href="#models-and-cost">Cost</a> ·
|
|
38
|
+
<a href="#faq">FAQ</a>
|
|
39
|
+
</p>
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
<!-- DEMO GIF — record after the first real PR run.
|
|
44
|
+
File: .github/assets/demo.gif (1280x720, ≤ 8 MB, ≤ 30 s)
|
|
45
|
+
Drop the file in and uncomment the <p> tag below.
|
|
46
|
+
<p align="center">
|
|
47
|
+
<img src=".github/assets/demo.gif" alt="autoglot in action: edit en.json, push, watch the bot translate and commit." width="820">
|
|
48
|
+
</p>
|
|
49
|
+
-->
|
|
50
|
+
|
|
51
|
+
## What it is (and isn't)
|
|
52
|
+
|
|
53
|
+
autoglot **fills in your missing locale files**. You write `messages/en.json`. autoglot writes `messages/es.json`, `messages/de.json`, etc. by calling Claude on every push.
|
|
54
|
+
|
|
55
|
+
It is **not** a runtime i18n library. You still need [`next-intl`](https://next-intl.dev/), [`react-i18next`](https://react.i18next.com/), [`vue-i18n`](https://vue-i18n.intlify.dev/), or similar to read those JSON files in your app and resolve `t("...")` calls. autoglot is the translator; your i18n library is the reader.
|
|
56
|
+
|
|
57
|
+
## Why
|
|
58
|
+
|
|
59
|
+
- **Zero npm dependencies.** Single Node 20+ script. Auditable in 30 minutes.
|
|
60
|
+
- **Incremental.** A YAML lock file fingerprints every English string; only changed/new keys are sent to the LLM.
|
|
61
|
+
- **Free, except for the API key.** No SaaS, no rate limits, no quota. You pay Anthropic directly — typical PR costs **under a cent**.
|
|
62
|
+
- **CI-native.** Ships as a GitHub Action. The bot commits the translated JSON back to your branch and posts a cost report on the PR.
|
|
63
|
+
- **Framework-agnostic.** Works with `next-intl`, `react-i18next`, `vue-i18n`, `i18next`, anything that reads a flat-or-nested JSON message catalog.
|
|
64
|
+
|
|
65
|
+
<!-- PR COMMENT — placeholder mockup. Replace with a real screenshot once you have one.
|
|
66
|
+
File: .github/assets/pr-comment.png (1024x600). Until you do, the .svg mockup is fine. -->
|
|
67
|
+
<p align="center">
|
|
68
|
+
<img src=".github/assets/pr-comment.svg" alt="The bot posts a cost summary as a PR comment" width="720">
|
|
69
|
+
</p>
|
|
70
|
+
|
|
71
|
+
## Quickstart (GitHub Action)
|
|
72
|
+
|
|
73
|
+
```yaml
|
|
74
|
+
# .github/workflows/translate.yml
|
|
75
|
+
name: translate
|
|
76
|
+
on:
|
|
77
|
+
push:
|
|
78
|
+
branches: ["**"]
|
|
79
|
+
paths:
|
|
80
|
+
- messages/en.json
|
|
81
|
+
- translate.config.json
|
|
82
|
+
|
|
83
|
+
concurrency:
|
|
84
|
+
group: translate-${{ github.ref }}
|
|
85
|
+
cancel-in-progress: true
|
|
86
|
+
|
|
87
|
+
jobs:
|
|
88
|
+
translate:
|
|
89
|
+
runs-on: ubuntu-latest
|
|
90
|
+
permissions:
|
|
91
|
+
contents: write
|
|
92
|
+
pull-requests: write
|
|
93
|
+
steps:
|
|
94
|
+
- uses: actions/checkout@v4
|
|
95
|
+
- uses: ffcabbar/autoglot@v1
|
|
96
|
+
with:
|
|
97
|
+
anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json` in your repo, and create one empty `messages/<locale>.json` per language. On the next push, the bot will:
|
|
101
|
+
|
|
102
|
+
1. Diff `en.json` against the lock file (`md5` per key).
|
|
103
|
+
2. Send only changed/new keys to Claude.
|
|
104
|
+
3. Write each locale's JSON file.
|
|
105
|
+
4. Commit `chore(i18n): update translations` and post a cost summary on the PR.
|
|
106
|
+
|
|
107
|
+
## Quickstart (CLI, no GitHub)
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
npm install -D autoglot
|
|
111
|
+
echo '{ "greeting": "Hello, world!" }' > messages/en.json
|
|
112
|
+
echo '{}' > messages/es.json
|
|
113
|
+
echo '{}' > messages/de.json
|
|
114
|
+
|
|
115
|
+
ANTHROPIC_API_KEY=sk-ant-... npx autoglot
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
After the first run, `messages/es.json` and `messages/de.json` are populated, and `translate.lock` records what was translated.
|
|
119
|
+
|
|
120
|
+
## vs. the alternatives
|
|
121
|
+
|
|
122
|
+
| | **autoglot** | Languine | Lokalise / Crowdin / Phrase | i18n-ai-translate |
|
|
123
|
+
|---|:---:|:---:|:---:|:---:|
|
|
124
|
+
| License | **MIT** | AGPL-3.0 | Proprietary | MIT |
|
|
125
|
+
| SaaS account required | **No** | No (CLI) | **Yes** | No |
|
|
126
|
+
| Hosted dashboard | None | Optional | Required | None |
|
|
127
|
+
| GitHub Action | **Yes (built-in)** | Yes | Plugin | No |
|
|
128
|
+
| Bot commits the diff back | **Yes** | Yes | Manual | No |
|
|
129
|
+
| Cost per ~1k-key PR | **<$0.01** | <$0.01 | $5–$50 | <$0.01 |
|
|
130
|
+
| Dependencies | **0** | many | n/a (SaaS) | several |
|
|
131
|
+
| Multi-provider | v0.2 | Yes | n/a | Yes |
|
|
132
|
+
| Formats | JSON | 15+ | 15+ | JSON |
|
|
133
|
+
| Self-hosted | **Yes** | Yes | No | Yes |
|
|
134
|
+
|
|
135
|
+
## Configuration
|
|
136
|
+
|
|
137
|
+
`translate.config.json` (optional — sensible defaults):
|
|
138
|
+
|
|
139
|
+
```json
|
|
140
|
+
{
|
|
141
|
+
"source": "messages/en.json",
|
|
142
|
+
"messagesDir": "messages",
|
|
143
|
+
"lockFile": "translate.lock",
|
|
144
|
+
"model": "claude-haiku-4-5",
|
|
145
|
+
"glossary": ["MyApp", "Stripe", "API"],
|
|
146
|
+
"namespaceContext": {
|
|
147
|
+
"checkout": "Payment checkout form copy.",
|
|
148
|
+
"dashboard": "Merchant dashboard navigation and forms."
|
|
149
|
+
},
|
|
150
|
+
"namespaces": {
|
|
151
|
+
"dashboard": ["es", "de"]
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
| Field | Default | What it does |
|
|
157
|
+
|---|---|---|
|
|
158
|
+
| `source` | `messages/en.json` | Path to your source-of-truth locale file. |
|
|
159
|
+
| `messagesDir` | `messages` | Where the other `<locale>.json` files live. |
|
|
160
|
+
| `lockFile` | `translate.lock` | Where to store md5 fingerprints. Commit it. |
|
|
161
|
+
| `model` | `claude-haiku-4-5` | Anthropic model. Haiku is recommended; quality is excellent. |
|
|
162
|
+
| `glossary` | `[]` | Product/brand names the model must keep verbatim. |
|
|
163
|
+
| `namespaceContext` | `{}` | Hint the model about each top-level namespace. Improves quality. |
|
|
164
|
+
| `namespaces` | `{}` | Deny-list. Listed namespaces are restricted to listed locales; unlisted namespaces translate to all locales. |
|
|
165
|
+
|
|
166
|
+
## CLI flags
|
|
167
|
+
|
|
168
|
+
```
|
|
169
|
+
--check CI gate: exit 1 if lock != source. No AI call.
|
|
170
|
+
--dry-run Show plan, no AI call, no writes.
|
|
171
|
+
--quiet Suppress per-locale and per-chunk progress. CI keeps verbose logs.
|
|
172
|
+
--locales=de,fr Restrict run to specific locales.
|
|
173
|
+
--model=<id> Override the configured model.
|
|
174
|
+
--source=<path> Override config.source.
|
|
175
|
+
--messages-dir=<path> Override config.messagesDir.
|
|
176
|
+
--lock-file=<path> Override config.lockFile.
|
|
177
|
+
--config=<path> Custom config file path.
|
|
178
|
+
--import-languine[=path] Seed our lock file from a `languine.lock`.
|
|
179
|
+
-v, --version Print version and exit.
|
|
180
|
+
-h, --help Print help and exit.
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## Models and cost
|
|
184
|
+
|
|
185
|
+
| Model | Cost (per 1M tokens) | When to use |
|
|
186
|
+
|---|---|---|
|
|
187
|
+
| `claude-haiku-4-5` *(default)* | $1 in / $5 out | Everything. |
|
|
188
|
+
| `claude-sonnet-4-6` | $3 in / $15 out | A specific locale where Haiku quality slips. |
|
|
189
|
+
| `claude-opus-4-7` | $15 in / $75 out | You almost certainly don't need this. |
|
|
190
|
+
|
|
191
|
+
Typical PR (1–3 changed keys × 30 locales) costs under a cent on Haiku. A first-run backfill of ~2,000 keys × 30 locales is around $1–$3.
|
|
192
|
+
|
|
193
|
+
## Migrating from Languine
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
npx autoglot --import-languine=languine.lock
|
|
197
|
+
rm languine.json languine.lock
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Then replace your Languine workflow with the one above. The lock file will be in sync — no re-translation, no re-cost.
|
|
201
|
+
|
|
202
|
+
## How it works
|
|
203
|
+
|
|
204
|
+
<!-- ARCHITECTURE DIAGRAM (optional)
|
|
205
|
+
File: .github/assets/how-it-works.svg
|
|
206
|
+
Prompt: "A simple horizontal flowchart with 5 boxes connected by arrows:
|
|
207
|
+
[en.json edit] → [diff vs lock file] → [Anthropic API: only changed keys]
|
|
208
|
+
→ [merge into <locale>.json files] → [bot commit + PR comment].
|
|
209
|
+
Monochrome dark theme, purple accent (#8b5cf6). Looks like a Linear
|
|
210
|
+
or Stripe docs diagram. Inter font."
|
|
211
|
+
-->
|
|
212
|
+
<p align="center">
|
|
213
|
+
<img src=".github/assets/how-it-works.svg" alt="autoglot architecture: diff → translate → merge → commit" width="1100">
|
|
214
|
+
</p>
|
|
215
|
+
|
|
216
|
+
1. **Flatten** your source JSON to dotted keys: `{ "checkout.cta": "Pay now" }`.
|
|
217
|
+
2. **Diff** each value's md5 against the lock file → `new`, `changed`, `orphan` (deleted) keys.
|
|
218
|
+
3. **For each locale**: collect missing + changed keys, chunk into batches of 200, call Anthropic with forced [tool use](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) so the response is structured JSON (not freeform).
|
|
219
|
+
4. **Validate** placeholders (`{name}`) match between source and translation; retry on mismatch.
|
|
220
|
+
5. **Merge** translations back into the locale's JSON, preserving source key order, dropping orphan keys.
|
|
221
|
+
6. **Update** the lock file, write a markdown summary, exit.
|
|
222
|
+
|
|
223
|
+
In CI, the action then commits the diff and posts the cost summary on the PR.
|
|
224
|
+
|
|
225
|
+
## FAQ
|
|
226
|
+
|
|
227
|
+
<details>
|
|
228
|
+
<summary><strong>Does it work with my framework?</strong></summary>
|
|
229
|
+
|
|
230
|
+
If your i18n library reads JSON files (`next-intl`, `react-i18next`, `vue-i18n`, `i18next`, `formatjs`, `lingui`, `react-intl`, ...), yes. autoglot is format-agnostic about how the JSON is structured.
|
|
231
|
+
|
|
232
|
+
</details>
|
|
233
|
+
|
|
234
|
+
<details>
|
|
235
|
+
<summary><strong>What about ICU plurals, dates, gender?</strong></summary>
|
|
236
|
+
|
|
237
|
+
ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt to Claude. The placeholder validator covers `{name}` tokens; for ICU we rely on the model — in practice Haiku 4.5 handles it correctly. If you spot a regression, open an issue.
|
|
238
|
+
|
|
239
|
+
</details>
|
|
240
|
+
|
|
241
|
+
<details>
|
|
242
|
+
<summary><strong>Why JSON only?</strong></summary>
|
|
243
|
+
|
|
244
|
+
JSON covers ~95% of JS app i18n. Adding YAML / `.strings` / Android XML triples the test surface. We'd rather do JSON well than 15 formats badly. v0.3+ if there's demand.
|
|
245
|
+
|
|
246
|
+
</details>
|
|
247
|
+
|
|
248
|
+
<details>
|
|
249
|
+
<summary><strong>Why not OpenAI / Gemini?</strong></summary>
|
|
250
|
+
|
|
251
|
+
Coming in v0.2. Anthropic's tool use is the most stable for structured output today, which is why v0.1 ships Anthropic-only. Each provider's tool semantics differ subtly; we'd rather wait until we have tests for all three.
|
|
252
|
+
|
|
253
|
+
</details>
|
|
254
|
+
|
|
255
|
+
<details>
|
|
256
|
+
<summary><strong>Is the bot a "real" GitHub bot with an avatar?</strong></summary>
|
|
257
|
+
|
|
258
|
+
Not yet. v0.1 commits as `github-actions[bot]` (the default rabbit avatar). A real GitHub App with the autoglot logo is on the roadmap — see `docs/distribution.md` for the four levels of bot identity and why we chose Level 1 to start.
|
|
259
|
+
|
|
260
|
+
</details>
|
|
261
|
+
|
|
262
|
+
<details>
|
|
263
|
+
<summary><strong>Can I run it without GitHub?</strong></summary>
|
|
264
|
+
|
|
265
|
+
Yes. `npx autoglot` works in any CI (GitLab, CircleCI, Jenkins, your laptop). The GitHub Action is just a thin wrapper that adds the `git commit` + `gh pr comment` ritual.
|
|
266
|
+
|
|
267
|
+
</details>
|
|
268
|
+
|
|
269
|
+
<details>
|
|
270
|
+
<summary><strong>How do I keep brand names from being translated?</strong></summary>
|
|
271
|
+
|
|
272
|
+
Add them to `glossary` in `translate.config.json`. They'll be passed to Claude with explicit instruction to leave them verbatim.
|
|
273
|
+
|
|
274
|
+
</details>
|
|
275
|
+
|
|
276
|
+
## Roadmap
|
|
277
|
+
|
|
278
|
+
- [x] **v0.1** — Anthropic, JSON, GitHub Action, Languine importer, parallel locales, lock file
|
|
279
|
+
- [ ] **v0.2** — Multi-provider (OpenAI, Gemini), provider-fallback chain
|
|
280
|
+
- [ ] **v0.3** — YAML / `.strings` / Android XML formats (gated on demand)
|
|
281
|
+
- [ ] **v0.4** — Hosted GitHub App (real bot avatar, one-click install) — paid tier, OSS still first-class
|
|
282
|
+
|
|
283
|
+
See [`RELEASE_PLAN.md`](./RELEASE_PLAN.md) for the full plan.
|
|
284
|
+
|
|
285
|
+
## Contributing
|
|
286
|
+
|
|
287
|
+
Issues, PRs, and bug reports welcome. The codebase is intentionally tiny:
|
|
288
|
+
|
|
289
|
+
- `bin/translate.mjs` (≈ 500 lines) — the entire engine
|
|
290
|
+
- `bin/helpers.mjs` — pure helpers
|
|
291
|
+
- `tests/helpers.test.mjs` — `node:test` suite, runs offline
|
|
292
|
+
|
|
293
|
+
```bash
|
|
294
|
+
git clone https://github.com/ffcabbar/autoglot
|
|
295
|
+
cd autoglot
|
|
296
|
+
npm test # offline
|
|
297
|
+
cd examples/basic && node ../../bin/translate.mjs --dry-run
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
## Sponsor
|
|
301
|
+
|
|
302
|
+
If `autoglot` saves you the cost of a Languine subscription, consider [sponsoring on GitHub](https://github.com/sponsors/ffcabbar). The whole project is one person's evenings.
|
|
303
|
+
|
|
304
|
+
## License
|
|
305
|
+
|
|
306
|
+
[MIT](./LICENSE) © ffcabbar
|
|
307
|
+
|
|
308
|
+
---
|
|
309
|
+
|
|
310
|
+
<p align="center">
|
|
311
|
+
<sub>If autoglot helped you, a ⭐ on the repo is the best way to say thanks.</sub>
|
|
312
|
+
</p>
|
package/bin/helpers.mjs
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Pure helpers extracted from translate.mjs so they can be unit-tested.
|
|
2
|
+
// No side effects, no I/O, no process.exit. Anything that touches fs,
|
|
3
|
+
// network, or process.* belongs in translate.mjs.
|
|
4
|
+
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
|
|
7
|
+
export function parseArgs(argv) {
|
|
8
|
+
const out = {};
|
|
9
|
+
for (const a of argv) {
|
|
10
|
+
if (!a.startsWith("--")) continue;
|
|
11
|
+
const eq = a.indexOf("=");
|
|
12
|
+
if (eq === -1) out[a.slice(2)] = true;
|
|
13
|
+
else out[a.slice(2, eq)] = a.slice(eq + 1);
|
|
14
|
+
}
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function flatten(obj, prefix = "", out = {}) {
|
|
19
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
20
|
+
const key = prefix ? `${prefix}.${k}` : k;
|
|
21
|
+
if (v && typeof v === "object" && !Array.isArray(v)) flatten(v, key, out);
|
|
22
|
+
else out[key] = v;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function mergeOrdered(source, existing, translations) {
|
|
28
|
+
const out = {};
|
|
29
|
+
for (const k of Object.keys(source)) {
|
|
30
|
+
if (source[k] && typeof source[k] === "object" && !Array.isArray(source[k])) {
|
|
31
|
+
out[k] = mergeOrdered(source[k], existing[k] || {}, translationsPrefix(translations, k));
|
|
32
|
+
} else {
|
|
33
|
+
out[k] = pickTranslation(translations, existing, k);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function translationsPrefix(translations, prefix) {
|
|
40
|
+
const out = {};
|
|
41
|
+
const p = `${prefix}.`;
|
|
42
|
+
for (const k of Object.keys(translations)) {
|
|
43
|
+
if (k === prefix) out[""] = translations[k];
|
|
44
|
+
else if (k.startsWith(p)) out[k.slice(p.length)] = translations[k];
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function pickTranslation(translations, existing, key) {
|
|
50
|
+
if (key in translations) return translations[key];
|
|
51
|
+
if (existing && key in existing) return existing[key];
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function extractPlaceholders(s) {
|
|
56
|
+
// Only validates plain {name} placeholders. ICU plural/select syntax is
|
|
57
|
+
// preserved by the LLM per the system prompt; validating nested ICU
|
|
58
|
+
// structure with a regex is unreliable (matches differ across languages).
|
|
59
|
+
const set = new Set();
|
|
60
|
+
const re = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
|
|
61
|
+
let m;
|
|
62
|
+
while ((m = re.exec(s)) !== null) set.add(m[1]);
|
|
63
|
+
return set;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function setsEqual(a, b) {
|
|
67
|
+
if (a.size !== b.size) return false;
|
|
68
|
+
for (const v of a) if (!b.has(v)) return false;
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function hash(s) {
|
|
73
|
+
return createHash("md5").update(String(s)).digest("hex");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function chunk(arr, size) {
|
|
77
|
+
const out = [];
|
|
78
|
+
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function parseLockYaml(raw, defaultSource = "") {
|
|
83
|
+
const lock = { version: 1, source: defaultSource, hashes: {} };
|
|
84
|
+
let inHashes = false;
|
|
85
|
+
for (const rawLine of raw.split("\n")) {
|
|
86
|
+
const line = rawLine.replace(/\r$/, "");
|
|
87
|
+
if (!line || /^\s*#/.test(line)) continue;
|
|
88
|
+
if (!inHashes) {
|
|
89
|
+
let m = line.match(/^version:\s*(\d+)\s*$/);
|
|
90
|
+
if (m) { lock.version = Number(m[1]); continue; }
|
|
91
|
+
m = line.match(/^source:\s*(.+?)\s*$/);
|
|
92
|
+
if (m) { lock.source = m[1]; continue; }
|
|
93
|
+
if (/^hashes:\s*$/.test(line)) { inHashes = true; continue; }
|
|
94
|
+
} else {
|
|
95
|
+
const m = line.match(/^\s{2}(\S+):\s*(\S+)\s*$/);
|
|
96
|
+
if (m) lock.hashes[m[1]] = m[2];
|
|
97
|
+
else if (!/^\s/.test(line)) inHashes = false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return lock;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function dumpLockYaml(lock) {
|
|
104
|
+
let out = `version: ${lock.version}\nsource: ${lock.source}\nhashes:\n`;
|
|
105
|
+
for (const key of Object.keys(lock.hashes)) {
|
|
106
|
+
out += ` ${key}: ${lock.hashes[key]}\n`;
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function allowedTopLevelNamespaces(source, locale, cfg) {
|
|
112
|
+
const out = new Set();
|
|
113
|
+
for (const ns of Object.keys(source)) {
|
|
114
|
+
const restriction = cfg.namespaces?.[ns];
|
|
115
|
+
if (!restriction || restriction.includes(locale)) out.add(ns);
|
|
116
|
+
}
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function pickAllowedSource(source, allowedNs) {
|
|
121
|
+
const out = {};
|
|
122
|
+
for (const k of Object.keys(source)) if (allowedNs.has(k)) out[k] = source[k];
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// pLimit — minimal zero-dep concurrency limiter.
|
|
127
|
+
// Returns a function that, when invoked with a thunk `() => Promise<T>`,
|
|
128
|
+
// queues it and resolves with the eventual value. At most `n` thunks
|
|
129
|
+
// run concurrently. Used in translate.mjs to parallelize the locale loop.
|
|
130
|
+
export function pLimit(n) {
|
|
131
|
+
if (!Number.isFinite(n) || n < 1) throw new Error(`pLimit: invalid concurrency ${n}`);
|
|
132
|
+
let active = 0;
|
|
133
|
+
const queue = [];
|
|
134
|
+
const next = () => {
|
|
135
|
+
if (active >= n || queue.length === 0) return;
|
|
136
|
+
active++;
|
|
137
|
+
const { thunk, resolve, reject } = queue.shift();
|
|
138
|
+
Promise.resolve().then(thunk).then(
|
|
139
|
+
(v) => { active--; resolve(v); next(); },
|
|
140
|
+
(e) => { active--; reject(e); next(); },
|
|
141
|
+
);
|
|
142
|
+
};
|
|
143
|
+
return (thunk) => new Promise((resolve, reject) => {
|
|
144
|
+
queue.push({ thunk, resolve, reject });
|
|
145
|
+
next();
|
|
146
|
+
});
|
|
147
|
+
}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// AI translation runner for i18n locale JSON files.
|
|
3
|
+
// Zero runtime deps. Uses Anthropic's messages API + a tiny YAML lock file.
|
|
4
|
+
//
|
|
5
|
+
// What it does
|
|
6
|
+
// Reads <source> (your en.json), diffs it against <lock-file> (md5 per key),
|
|
7
|
+
// translates new/changed keys with an LLM, and writes results into
|
|
8
|
+
// <messages-dir>/<locale>.json for every target locale. Keys deleted
|
|
9
|
+
// from the source are stripped from every locale at zero AI cost.
|
|
10
|
+
// Drop-in replacement for Languine.
|
|
11
|
+
//
|
|
12
|
+
// Quickstart
|
|
13
|
+
// 1. Drop a translate.config.json next to your package.json:
|
|
14
|
+
// {
|
|
15
|
+
// "source": "messages/en.json",
|
|
16
|
+
// "messagesDir": "messages",
|
|
17
|
+
// "lockFile": "translate.lock"
|
|
18
|
+
// }
|
|
19
|
+
// 2. Set ANTHROPIC_API_KEY in your env.
|
|
20
|
+
// 3. Run: npx <this-package>
|
|
21
|
+
//
|
|
22
|
+
// Flags
|
|
23
|
+
// --check CI gate: exit 1 if lock != source.
|
|
24
|
+
// --dry-run Show plan, no AI call, no writes.
|
|
25
|
+
// --locales=de,fr Restrict run to specific locales.
|
|
26
|
+
// --model=<id> Override the Anthropic model.
|
|
27
|
+
// --config=<path> Custom config file path.
|
|
28
|
+
// --source=<path> Override config.source.
|
|
29
|
+
// --messages-dir=<path> Override config.messagesDir.
|
|
30
|
+
// --lock-file=<path> Override config.lockFile.
|
|
31
|
+
// --import-languine[=<path>] Import a languine.lock to seed our lock file.
|
|
32
|
+
|
|
33
|
+
import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from "node:fs";
|
|
34
|
+
import { join, resolve, isAbsolute } from "node:path";
|
|
35
|
+
import { tmpdir } from "node:os";
|
|
36
|
+
import {
|
|
37
|
+
parseArgs,
|
|
38
|
+
flatten,
|
|
39
|
+
mergeOrdered,
|
|
40
|
+
extractPlaceholders,
|
|
41
|
+
setsEqual,
|
|
42
|
+
hash,
|
|
43
|
+
chunk,
|
|
44
|
+
parseLockYaml,
|
|
45
|
+
dumpLockYaml,
|
|
46
|
+
allowedTopLevelNamespaces,
|
|
47
|
+
pickAllowedSource,
|
|
48
|
+
pLimit,
|
|
49
|
+
} from "./helpers.mjs";
|
|
50
|
+
|
|
51
|
+
// --- Constants ------------------------------------------------------------
|
|
52
|
+
const HELP_TEXT = `autoglot — AI-powered i18n translation bot
|
|
53
|
+
|
|
54
|
+
Usage
|
|
55
|
+
npx autoglot [flags]
|
|
56
|
+
|
|
57
|
+
Flags
|
|
58
|
+
--check CI gate: exit 1 if lock != source. No AI call.
|
|
59
|
+
--dry-run Show plan, no AI call, no writes.
|
|
60
|
+
--quiet Suppress per-locale progress (auto-disabled in CI).
|
|
61
|
+
--locales=de,fr Restrict run to specific locales.
|
|
62
|
+
--model=<id> Override the configured model (default: claude-haiku-4-5).
|
|
63
|
+
--source=<path> Override config.source (default: messages/en.json).
|
|
64
|
+
--messages-dir=<path> Override config.messagesDir (default: messages).
|
|
65
|
+
--lock-file=<path> Override config.lockFile (default: translate.lock).
|
|
66
|
+
--config=<path> Custom config file path (default: translate.config.json).
|
|
67
|
+
--import-languine[=<path>] Seed our lock file from a languine.lock and exit.
|
|
68
|
+
--summary-path=<path> Where to write the markdown summary.
|
|
69
|
+
-v, --version Print version and exit.
|
|
70
|
+
-h, --help Print this help and exit.
|
|
71
|
+
|
|
72
|
+
Environment
|
|
73
|
+
ANTHROPIC_API_KEY Required for real runs. Not needed for --check or --dry-run.
|
|
74
|
+
|
|
75
|
+
Docs
|
|
76
|
+
https://github.com/ffcabbar/autoglot
|
|
77
|
+
`;
|
|
78
|
+
const CHUNK_SIZE = 200;
|
|
79
|
+
const RATE_LIMIT_MAX_RETRIES = 5;
|
|
80
|
+
const LOCALE_CONCURRENCY = 8;
|
|
81
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
82
|
+
|
|
83
|
+
// USD per 1M tokens. Update when Anthropic pricing changes.
|
|
84
|
+
const PRICING = {
|
|
85
|
+
"claude-haiku-4-5": { input: 1.0, output: 5.0 },
|
|
86
|
+
"claude-sonnet-4-6": { input: 3.0, output: 15.0 },
|
|
87
|
+
"claude-opus-4-7": { input: 15.0, output: 75.0 },
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const LOCALE_DISPLAY = new Intl.DisplayNames(["en"], { type: "language" });
|
|
91
|
+
|
|
92
|
+
// --- CLI ------------------------------------------------------------------
|
|
93
|
+
const args = parseArgs(process.argv.slice(2));
|
|
94
|
+
const CWD = process.cwd();
|
|
95
|
+
|
|
96
|
+
if (args.version || args.v) {
|
|
97
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
98
|
+
console.log(pkg.version);
|
|
99
|
+
process.exit(0);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (args.help || args.h) {
|
|
103
|
+
console.log(HELP_TEXT);
|
|
104
|
+
process.exit(0);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const CONFIG_PATH = resolvePath(args.config || "translate.config.json");
|
|
108
|
+
|
|
109
|
+
const config = loadConfig(CONFIG_PATH);
|
|
110
|
+
|
|
111
|
+
const SOURCE_FILE = resolvePath(args.source || config.source || "messages/en.json");
|
|
112
|
+
const MESSAGES_DIR = resolvePath(args["messages-dir"] || config.messagesDir || "messages");
|
|
113
|
+
const LOCK_FILE = resolvePath(args["lock-file"] || config.lockFile || "translate.lock");
|
|
114
|
+
const SUMMARY_FILE = args["summary-path"]
|
|
115
|
+
? resolvePath(args["summary-path"])
|
|
116
|
+
: join(tmpdir(), "translate-summary.md");
|
|
117
|
+
const STEP_SUMMARY = process.env.GITHUB_STEP_SUMMARY;
|
|
118
|
+
const MODEL = args.model || config.model || "claude-haiku-4-5";
|
|
119
|
+
// --quiet suppresses per-locale and per-chunk progress lines. The summary
|
|
120
|
+
// (totals + per-locale table) always prints. CI runs default to verbose so
|
|
121
|
+
// workflow logs stay actionable when something goes wrong.
|
|
122
|
+
const QUIET = args.quiet === true && !process.env.CI;
|
|
123
|
+
const verbose = (...m) => { if (!QUIET) console.log(...m); };
|
|
124
|
+
|
|
125
|
+
if (!PRICING[MODEL]) {
|
|
126
|
+
console.error(`[translate] Unknown model '${MODEL}'. Known: ${Object.keys(PRICING).join(", ")}`);
|
|
127
|
+
process.exit(1);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if ("import-languine" in args) {
|
|
131
|
+
const src = typeof args["import-languine"] === "string"
|
|
132
|
+
? resolvePath(args["import-languine"])
|
|
133
|
+
: resolvePath("languine.lock");
|
|
134
|
+
importLanguineLock(src);
|
|
135
|
+
process.exit(0);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
await run();
|
|
139
|
+
|
|
140
|
+
// --- Main -----------------------------------------------------------------
|
|
141
|
+
async function run() {
|
|
142
|
+
if (!existsSync(SOURCE_FILE)) {
|
|
143
|
+
console.error(`[translate] Source file not found: ${SOURCE_FILE}`);
|
|
144
|
+
console.error(`[translate] Set "source" in ${CONFIG_PATH} or pass --source=<path>.`);
|
|
145
|
+
process.exit(1);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const source = readJSON(SOURCE_FILE);
|
|
149
|
+
const sourceFlat = flatten(source);
|
|
150
|
+
const lock = loadLock();
|
|
151
|
+
const targets = args.locales
|
|
152
|
+
? args.locales.split(",").map((s) => s.trim()).filter(Boolean)
|
|
153
|
+
: discoverTargetLocales();
|
|
154
|
+
|
|
155
|
+
const newDelta = [];
|
|
156
|
+
const changedDelta = [];
|
|
157
|
+
for (const key of Object.keys(sourceFlat)) {
|
|
158
|
+
const h = hash(sourceFlat[key]);
|
|
159
|
+
if (!lock.hashes[key]) newDelta.push(key);
|
|
160
|
+
else if (lock.hashes[key] !== h) changedDelta.push(key);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
console.log(`[translate] source: ${newDelta.length} new keys, ${changedDelta.length} modified (${newDelta.length + changedDelta.length} total delta)`);
|
|
164
|
+
if (targets.length === 0) {
|
|
165
|
+
console.log("[translate] No target locales found — drop a <locale>.json into messagesDir.");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (args.check) {
|
|
169
|
+
if (newDelta.length + changedDelta.length === 0) {
|
|
170
|
+
console.log("[translate] All target locales up to date.");
|
|
171
|
+
process.exit(0);
|
|
172
|
+
}
|
|
173
|
+
console.log("[translate] Delta keys:", [...newDelta, ...changedDelta].join(", "));
|
|
174
|
+
process.exit(1);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!process.env.ANTHROPIC_API_KEY && !args["dry-run"]) {
|
|
178
|
+
console.error("[translate] ANTHROPIC_API_KEY is not set.");
|
|
179
|
+
process.exit(1);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (!existsSync(MESSAGES_DIR)) mkdirSync(MESSAGES_DIR, { recursive: true });
|
|
183
|
+
|
|
184
|
+
// Per-locale work runs in parallel up to LOCALE_CONCURRENCY. Each locale
|
|
185
|
+
// writes its own file, so there's no contention. Aggregation into
|
|
186
|
+
// perLocale/totals happens at synchronous points (push, +=) which are
|
|
187
|
+
// safe in single-threaded JS.
|
|
188
|
+
const perLocale = [];
|
|
189
|
+
let totalIn = 0, totalOut = 0, totalCost = 0, skipped = 0;
|
|
190
|
+
const limit = pLimit(LOCALE_CONCURRENCY);
|
|
191
|
+
|
|
192
|
+
async function processLocale(locale) {
|
|
193
|
+
const targetPath = join(MESSAGES_DIR, `${locale}.json`);
|
|
194
|
+
const existing = existsSync(targetPath) ? readJSON(targetPath) : {};
|
|
195
|
+
const existingFlat = flatten(existing);
|
|
196
|
+
|
|
197
|
+
const allowedNs = allowedTopLevelNamespaces(source, locale, config);
|
|
198
|
+
const isAllowed = (k) => allowedNs.has(k.split(".")[0]);
|
|
199
|
+
|
|
200
|
+
const missing = Object.keys(sourceFlat).filter((k) => isAllowed(k) && !(k in existingFlat));
|
|
201
|
+
const delta = [...newDelta, ...changedDelta].filter(isAllowed);
|
|
202
|
+
const keysToTranslate = Array.from(new Set([...missing, ...delta]));
|
|
203
|
+
|
|
204
|
+
const filteredSource = pickAllowedSource(source, allowedNs);
|
|
205
|
+
const hasOrphans = Object.keys(existingFlat).some((k) => !(k in sourceFlat) || !isAllowed(k));
|
|
206
|
+
|
|
207
|
+
if (keysToTranslate.length === 0) {
|
|
208
|
+
if (!hasOrphans) {
|
|
209
|
+
verbose(`[translate] ${locale.padEnd(6)} → up to date (skipped)`);
|
|
210
|
+
skipped++;
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (args["dry-run"]) {
|
|
214
|
+
verbose(`[translate] ${locale.padEnd(6)} → would remove orphan keys (dry-run)`);
|
|
215
|
+
perLocale.push({ locale, keys: 0, inTok: 0, outTok: 0, cost: 0 });
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const merged = mergeOrdered(filteredSource, existing, {});
|
|
219
|
+
writeFileSync(targetPath, JSON.stringify(merged, null, 2) + "\n");
|
|
220
|
+
verbose(`[translate] ${locale.padEnd(6)} → removed orphan keys`);
|
|
221
|
+
perLocale.push({ locale, keys: 0, inTok: 0, outTok: 0, cost: 0 });
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
if (args["dry-run"]) {
|
|
226
|
+
verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys (dry-run)`);
|
|
227
|
+
perLocale.push({ locale, keys: keysToTranslate.length, inTok: 0, outTok: 0, cost: 0 });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const chunks = chunk(keysToTranslate, CHUNK_SIZE);
|
|
232
|
+
const translations = {};
|
|
233
|
+
let usageIn = 0, usageOut = 0;
|
|
234
|
+
for (const [idx, keys] of chunks.entries()) {
|
|
235
|
+
const payload = Object.fromEntries(keys.map((k) => [k, sourceFlat[k]]));
|
|
236
|
+
if (chunks.length > 1) {
|
|
237
|
+
verbose(`[translate] ${locale.padEnd(6)} → chunk ${idx + 1}/${chunks.length} (${keys.length} keys)`);
|
|
238
|
+
}
|
|
239
|
+
const { translations: t, usage } = await translate(locale, payload);
|
|
240
|
+
Object.assign(translations, t);
|
|
241
|
+
usageIn += usage.input_tokens;
|
|
242
|
+
usageOut += usage.output_tokens;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const merged = mergeOrdered(filteredSource, existing, translations);
|
|
246
|
+
writeFileSync(targetPath, JSON.stringify(merged, null, 2) + "\n");
|
|
247
|
+
|
|
248
|
+
const cost = (usageIn / 1e6) * PRICING[MODEL].input + (usageOut / 1e6) * PRICING[MODEL].output;
|
|
249
|
+
totalIn += usageIn;
|
|
250
|
+
totalOut += usageOut;
|
|
251
|
+
totalCost += cost;
|
|
252
|
+
perLocale.push({ locale, keys: keysToTranslate.length, inTok: usageIn, outTok: usageOut, cost });
|
|
253
|
+
verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys | in: ${usageIn} out: ${usageOut} | $${cost.toFixed(5)}`);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
await Promise.all(targets.map((locale) => limit(() => processLocale(locale))));
|
|
257
|
+
// Sort perLocale alphabetically so the summary table is stable across runs
|
|
258
|
+
// (parallel completion order would otherwise scramble it).
|
|
259
|
+
perLocale.sort((a, b) => a.locale.localeCompare(b.locale));
|
|
260
|
+
|
|
261
|
+
if (!args["dry-run"]) {
|
|
262
|
+
for (const key of Object.keys(sourceFlat)) lock.hashes[key] = hash(sourceFlat[key]);
|
|
263
|
+
for (const key of Object.keys(lock.hashes)) if (!(key in sourceFlat)) delete lock.hashes[key];
|
|
264
|
+
writeFileSync(LOCK_FILE, dumpLockYaml(lock));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const summary = renderSummary({
|
|
268
|
+
model: MODEL,
|
|
269
|
+
processed: perLocale.length,
|
|
270
|
+
skipped,
|
|
271
|
+
totalIn,
|
|
272
|
+
totalOut,
|
|
273
|
+
totalCost,
|
|
274
|
+
perLocale,
|
|
275
|
+
dryRun: !!args["dry-run"],
|
|
276
|
+
newKeys: newDelta.length,
|
|
277
|
+
modifiedKeys: changedDelta.length,
|
|
278
|
+
});
|
|
279
|
+
console.log("[translate] ──────────────────────────────────────");
|
|
280
|
+
console.log(summary.stdout);
|
|
281
|
+
if (STEP_SUMMARY) writeFileSync(STEP_SUMMARY, summary.markdown, { flag: "a" });
|
|
282
|
+
writeFileSync(SUMMARY_FILE, summary.markdown);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// --- Anthropic call -------------------------------------------------------
|
|
286
|
+
// Uses tool use (structured outputs) so the model can't corrupt the wire
|
|
287
|
+
// format with unescaped characters — the API returns `input` as a pre-parsed
|
|
288
|
+
// object, eliminating a whole class of JSON parse failures (e.g. a Lithuanian
|
|
289
|
+
// translation closing a quoted word with ASCII " instead of U+201D).
|
|
290
|
+
async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
|
|
291
|
+
const localeName = LOCALE_DISPLAY.of(locale) || locale;
|
|
292
|
+
const namespaces = new Set(Object.keys(payload).map((k) => k.split(".")[0]));
|
|
293
|
+
const nsCtx = [...namespaces]
|
|
294
|
+
.map((n) => `- ${n}: ${(config.namespaceContext && config.namespaceContext[n]) || "application copy"}`)
|
|
295
|
+
.join("\n");
|
|
296
|
+
|
|
297
|
+
const glossary = Array.isArray(config.glossary) && config.glossary.length
|
|
298
|
+
? ` Keep these product names verbatim: ${config.glossary.join(", ")}.`
|
|
299
|
+
: "";
|
|
300
|
+
|
|
301
|
+
const system = `You are a professional localization engineer. Translate English values into ${localeName}. Preserve all placeholders like {name}, {count} exactly. Preserve ICU plural syntax verbatim ({count, plural, one {...} other {...}} — never translate one/other/few/many/zero or the # symbol).${glossary} Call the emit_translations tool with every input key mapped to its translated string — do not write prose outside the tool call.`;
|
|
302
|
+
|
|
303
|
+
const user = `Target locale: ${localeName} (${locale}).\nNamespace context:\n${nsCtx}\n\nTranslate:\n${JSON.stringify(payload, null, 2)}`;
|
|
304
|
+
|
|
305
|
+
const res = await fetch("https://api.anthropic.com/v1/messages", {
|
|
306
|
+
method: "POST",
|
|
307
|
+
headers: {
|
|
308
|
+
"content-type": "application/json",
|
|
309
|
+
"x-api-key": process.env.ANTHROPIC_API_KEY,
|
|
310
|
+
"anthropic-version": "2023-06-01",
|
|
311
|
+
},
|
|
312
|
+
body: JSON.stringify({
|
|
313
|
+
model: MODEL,
|
|
314
|
+
max_tokens: 8192,
|
|
315
|
+
temperature: 0,
|
|
316
|
+
system,
|
|
317
|
+
messages: [{ role: "user", content: user }],
|
|
318
|
+
tools: [{
|
|
319
|
+
name: "emit_translations",
|
|
320
|
+
description: `Emit ${localeName} translations keyed by the exact input dotted keys.`,
|
|
321
|
+
input_schema: {
|
|
322
|
+
type: "object",
|
|
323
|
+
additionalProperties: { type: "string" },
|
|
324
|
+
},
|
|
325
|
+
}],
|
|
326
|
+
tool_choice: { type: "tool", name: "emit_translations" },
|
|
327
|
+
}),
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
if (!res.ok) {
|
|
331
|
+
if (res.status === 429 && rateAttempt < RATE_LIMIT_MAX_RETRIES) {
|
|
332
|
+
const retryAfterSec = Number(res.headers.get("retry-after")) || 60;
|
|
333
|
+
console.warn(`[translate] ${locale}: rate limited (429), sleeping ${retryAfterSec}s (retry ${rateAttempt + 1}/${RATE_LIMIT_MAX_RETRIES})`);
|
|
334
|
+
await sleep(retryAfterSec * 1000 + 500);
|
|
335
|
+
return translate(locale, payload, attempt, rateAttempt + 1);
|
|
336
|
+
}
|
|
337
|
+
throw new Error(`Anthropic API ${res.status}: ${await res.text()}`);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const body = await res.json();
|
|
341
|
+
const toolUse = body.content?.find((c) => c.type === "tool_use");
|
|
342
|
+
if (!toolUse || typeof toolUse.input !== "object" || toolUse.input === null) {
|
|
343
|
+
if (attempt >= 2) throw new Error(`${locale}: no tool_use block in response\nRaw:\n${JSON.stringify(body.content)}`);
|
|
344
|
+
console.warn(`[translate] ${locale} → missing tool_use block, retrying once`);
|
|
345
|
+
return translate(locale, payload, attempt + 1);
|
|
346
|
+
}
|
|
347
|
+
const translations = toolUse.input;
|
|
348
|
+
|
|
349
|
+
for (const key of Object.keys(payload)) {
|
|
350
|
+
if (typeof translations[key] !== "string") {
|
|
351
|
+
if (attempt < 2) return translate(locale, payload, attempt + 1);
|
|
352
|
+
console.warn(`[translate] ${locale}: '${key}' omitted by model, using source value verbatim`);
|
|
353
|
+
translations[key] = payload[key];
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
const srcP = extractPlaceholders(payload[key]);
|
|
357
|
+
const outP = extractPlaceholders(translations[key]);
|
|
358
|
+
if (!setsEqual(srcP, outP)) {
|
|
359
|
+
if (attempt >= 2) throw new Error(`${locale}: placeholder mismatch on '${key}'. source=[${[...srcP].join(",")}] got=[${[...outP].join(",")}]`);
|
|
360
|
+
return translate(locale, payload, attempt + 1);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
return { translations, usage: body.usage };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// --- Helpers --------------------------------------------------------------
|
|
368
|
+
function resolvePath(p) {
|
|
369
|
+
return isAbsolute(p) ? p : resolve(CWD, p);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function readJSON(p) {
|
|
373
|
+
return JSON.parse(readFileSync(p, "utf8"));
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function loadLock() {
|
|
377
|
+
if (!existsSync(LOCK_FILE)) return { version: 1, source: SOURCE_FILE, hashes: {} };
|
|
378
|
+
return parseLockYaml(readFileSync(LOCK_FILE, "utf8"), SOURCE_FILE);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function loadConfig(p) {
|
|
382
|
+
if (!existsSync(p)) return { namespaces: {} };
|
|
383
|
+
try {
|
|
384
|
+
const parsed = JSON.parse(readFileSync(p, "utf8"));
|
|
385
|
+
return {
|
|
386
|
+
...parsed,
|
|
387
|
+
namespaces: parsed.namespaces || {},
|
|
388
|
+
};
|
|
389
|
+
} catch (err) {
|
|
390
|
+
console.error(`[translate] Failed to parse ${p}: ${err.message}`);
|
|
391
|
+
process.exit(1);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function discoverTargetLocales() {
|
|
396
|
+
if (!existsSync(MESSAGES_DIR)) return [];
|
|
397
|
+
const sourceBasename = SOURCE_FILE.split("/").pop();
|
|
398
|
+
return readdirSync(MESSAGES_DIR)
|
|
399
|
+
.filter((f) => f.endsWith(".json") && f !== sourceBasename)
|
|
400
|
+
.map((f) => f.slice(0, -5))
|
|
401
|
+
.sort();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function importLanguineLock(srcPath) {
|
|
405
|
+
if (!existsSync(srcPath)) {
|
|
406
|
+
console.error(`[translate] ${srcPath} not found.`);
|
|
407
|
+
process.exit(1);
|
|
408
|
+
}
|
|
409
|
+
const raw = readFileSync(srcPath, "utf8");
|
|
410
|
+
const hashes = {};
|
|
411
|
+
let inFile = false;
|
|
412
|
+
for (const line of raw.split("\n")) {
|
|
413
|
+
if (/^files:/.test(line)) continue;
|
|
414
|
+
if (/^\s{2}\S.*\.json:/.test(line)) { inFile = true; continue; }
|
|
415
|
+
if (/^\s{2}\S/.test(line)) { inFile = false; continue; }
|
|
416
|
+
if (!inFile) continue;
|
|
417
|
+
const m = line.match(/^\s{4}([^:]+):\s*(\S+)\s*$/);
|
|
418
|
+
if (m) hashes[m[1].trim()] = m[2].trim();
|
|
419
|
+
}
|
|
420
|
+
const lock = { version: 1, source: SOURCE_FILE, hashes };
|
|
421
|
+
writeFileSync(LOCK_FILE, dumpLockYaml(lock));
|
|
422
|
+
console.log(`[translate] Imported ${Object.keys(hashes).length} hashes from ${srcPath} → ${LOCK_FILE}`);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function renderSummary({ model, processed, skipped, totalIn, totalOut, totalCost, perLocale, dryRun, newKeys, modifiedKeys }) {
|
|
426
|
+
const stdout = [
|
|
427
|
+
`[translate] Model: ${model}${dryRun ? " (dry-run)" : ""}`,
|
|
428
|
+
`[translate] Locales: ${processed} processed, ${skipped} skipped`,
|
|
429
|
+
`[translate] Tokens: ${totalIn.toLocaleString()} in / ${totalOut.toLocaleString()} out`,
|
|
430
|
+
`[translate] Cost: $${totalCost.toFixed(4)}`,
|
|
431
|
+
].join("\n");
|
|
432
|
+
|
|
433
|
+
const rows = perLocale.map((r) => `| \`${r.locale}\` | ${r.keys} | ${r.inTok} | ${r.outTok} | $${r.cost.toFixed(5)} |`).join("\n");
|
|
434
|
+
const markdown = [
|
|
435
|
+
"## Translation run summary",
|
|
436
|
+
"",
|
|
437
|
+
describeDelta(newKeys, modifiedKeys),
|
|
438
|
+
"",
|
|
439
|
+
`- **Model:** \`${model}\`${dryRun ? " (dry-run)" : ""}`,
|
|
440
|
+
`- **Locales:** ${processed} processed, ${skipped} skipped (up to date)`,
|
|
441
|
+
`- **Tokens:** ${totalIn.toLocaleString()} in / ${totalOut.toLocaleString()} out`,
|
|
442
|
+
`- **Cost:** $${totalCost.toFixed(4)}`,
|
|
443
|
+
"",
|
|
444
|
+
"| Locale | Keys | Input tokens | Output tokens | Cost |",
|
|
445
|
+
"|---|---|---|---|---|",
|
|
446
|
+
rows || "| _none_ | | | | |",
|
|
447
|
+
"",
|
|
448
|
+
].join("\n");
|
|
449
|
+
|
|
450
|
+
return { stdout, markdown };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function describeDelta(newKeys, modifiedKeys) {
|
|
454
|
+
if (!newKeys && !modifiedKeys) return "No source changes detected — backfill only.";
|
|
455
|
+
const parts = [];
|
|
456
|
+
if (newKeys) parts.push(`**${newKeys} new ${newKeys === 1 ? "key" : "keys"}**`);
|
|
457
|
+
if (modifiedKeys) parts.push(`**${modifiedKeys} modified ${modifiedKeys === 1 ? "key" : "keys"}**`);
|
|
458
|
+
return `Detected ${parts.join(" and ")} in source.`;
|
|
459
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "autoglot",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AI-powered i18n translation bot. Diff your en.json on every push, translate only what changed, commit the JSON files back. MIT alternative to Languine, Lokalise, and Crowdin.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"autoglot": "bin/translate.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"README.md",
|
|
12
|
+
"LICENSE"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"translate": "node bin/translate.mjs",
|
|
16
|
+
"test": "node --test tests/helpers.test.mjs"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"i18n",
|
|
20
|
+
"l10n",
|
|
21
|
+
"localization",
|
|
22
|
+
"translation",
|
|
23
|
+
"auto-translate",
|
|
24
|
+
"automatic-translation",
|
|
25
|
+
"ai-translation",
|
|
26
|
+
"anthropic",
|
|
27
|
+
"claude",
|
|
28
|
+
"claude-haiku",
|
|
29
|
+
"claude-sonnet",
|
|
30
|
+
"github-action",
|
|
31
|
+
"github-actions",
|
|
32
|
+
"ci",
|
|
33
|
+
"cli",
|
|
34
|
+
"developer-tools",
|
|
35
|
+
"devtools",
|
|
36
|
+
"automation",
|
|
37
|
+
"next-intl",
|
|
38
|
+
"react-i18next",
|
|
39
|
+
"vue-i18n",
|
|
40
|
+
"i18next",
|
|
41
|
+
"languine",
|
|
42
|
+
"languine-alternative",
|
|
43
|
+
"lokalise-alternative",
|
|
44
|
+
"crowdin-alternative",
|
|
45
|
+
"phrase-alternative",
|
|
46
|
+
"transifex-alternative",
|
|
47
|
+
"translate-json",
|
|
48
|
+
"json-translation",
|
|
49
|
+
"messages",
|
|
50
|
+
"locale",
|
|
51
|
+
"locales",
|
|
52
|
+
"multilingual",
|
|
53
|
+
"open-source",
|
|
54
|
+
"mit"
|
|
55
|
+
],
|
|
56
|
+
"homepage": "https://github.com/ffcabbar/autoglot",
|
|
57
|
+
"repository": {
|
|
58
|
+
"type": "git",
|
|
59
|
+
"url": "git+https://github.com/ffcabbar/autoglot.git"
|
|
60
|
+
},
|
|
61
|
+
"bugs": {
|
|
62
|
+
"url": "https://github.com/ffcabbar/autoglot/issues"
|
|
63
|
+
},
|
|
64
|
+
"author": "ffcabbar",
|
|
65
|
+
"license": "MIT",
|
|
66
|
+
"engines": {
|
|
67
|
+
"node": ">=20.0.0"
|
|
68
|
+
}
|
|
69
|
+
}
|