autoglot 0.3.3 → 0.3.4
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 +39 -93
- package/bin/cli.mjs +7 -5
- package/bin/doctor.mjs +3 -1
- package/bin/extract.mjs +50 -15
- package/bin/helpers.mjs +2 -2
- package/bin/translate.mjs +119 -61
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,87 +1,40 @@
|
|
|
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
1
|
<h1 align="center">autoglot</h1>
|
|
17
2
|
|
|
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>
|
|
3
|
+
<p align="center"><strong>One source catalog. Translations that keep up with your code.</strong></p>
|
|
22
4
|
|
|
23
5
|
<p align="center">
|
|
24
|
-
<
|
|
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>
|
|
6
|
+
<img src=".github/assets/hero-prism.webp" width="900" alt="A glass prism splits a single violet beam toward three tiles with different writing systems">
|
|
30
7
|
</p>
|
|
31
8
|
|
|
32
9
|
<p align="center">
|
|
33
|
-
<a href="
|
|
34
|
-
<a href="
|
|
35
|
-
<a href="
|
|
36
|
-
<a href="
|
|
37
|
-
<a href="#models-and-cost">Cost</a> ·
|
|
38
|
-
<a href="#faq">FAQ</a>
|
|
10
|
+
<a href="https://www.npmjs.com/package/autoglot"><img src="https://img.shields.io/npm/v/autoglot?color=8b5cf6" alt="npm version"></a>
|
|
11
|
+
<a href="https://github.com/ffcabbar/autoglot/actions/workflows/ci.yml"><img src="https://github.com/ffcabbar/autoglot/actions/workflows/ci.yml/badge.svg" alt="CI status"></a>
|
|
12
|
+
<a href="https://github.com/ffcabbar/autoglot/tree/v1"><img src="https://img.shields.io/badge/GitHub%20Action-v1-8b5cf6?logo=githubactions&logoColor=white" alt="GitHub Action v1"></a>
|
|
13
|
+
<a href="LICENSE"><img src="https://img.shields.io/npm/l/autoglot?color=8b5cf6" alt="MIT license"></a>
|
|
39
14
|
</p>
|
|
40
15
|
|
|
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
16
|
<p align="center">
|
|
47
|
-
<
|
|
17
|
+
<a href="#quickstart">Quickstart</a> ·
|
|
18
|
+
<a href="#how-it-works">How it works</a> ·
|
|
19
|
+
<a href="#configuration">Configuration</a> ·
|
|
20
|
+
<a href="#cli-flags">CLI reference</a>
|
|
48
21
|
</p>
|
|
49
|
-
-->
|
|
50
22
|
|
|
51
|
-
|
|
23
|
+
autoglot translates JSON message catalogs with Claude. 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.
|
|
52
24
|
|
|
53
|
-
|
|
25
|
+
- **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 Anthropic with your API key.
|
|
27
|
+
- **Reviewable.** The GitHub Action commits JSON changes and can post token usage and estimated cost on an open PR.
|
|
54
28
|
|
|
55
|
-
|
|
29
|
+
## Quickstart
|
|
56
30
|
|
|
57
|
-
|
|
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 — `npx autoglot init` (30 seconds)
|
|
72
|
-
|
|
73
|
-
Inside any project:
|
|
31
|
+
Run this in your app directory and choose your target locales.
|
|
74
32
|
|
|
75
33
|
```bash
|
|
76
34
|
npx autoglot init
|
|
77
35
|
```
|
|
78
36
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
- detects your framework (see table below) and picks the right runtime i18n library to recommend
|
|
82
|
-
- asks which target locales to support (interactive multi-select)
|
|
83
|
-
- scaffolds `messages/en.json`, empty `messages/<locale>.json` per language, `translate.config.json`, the `.github/workflows/translate.yml` workflow, and framework-specific glue
|
|
84
|
-
- never overwrites existing files (skips them and prints a clear plan before writing)
|
|
37
|
+
Review the generated files, install the suggested i18n library, and add `ANTHROPIC_API_KEY` to your GitHub repository secrets. Edit `messages/en.json` and push your branch. For a local preview of the translation plan, run `npx autoglot --dry-run`.
|
|
85
38
|
|
|
86
39
|
### Supported frameworks
|
|
87
40
|
|
|
@@ -95,7 +48,7 @@ That's it. The CLI:
|
|
|
95
48
|
| **Vue / Nuxt** | `vue-i18n` | `src/i18n.ts` (Composition API mode) |
|
|
96
49
|
| **Generic / unknown** | (your choice) | Messages + workflow only — pair with any i18n library that reads JSON |
|
|
97
50
|
|
|
98
|
-
|
|
51
|
+
Install the runtime package and configure the GitHub secret.
|
|
99
52
|
|
|
100
53
|
```bash
|
|
101
54
|
# 1. Install the runtime i18n library — or let init do it:
|
|
@@ -108,8 +61,6 @@ gh secret set ANTHROPIC_API_KEY
|
|
|
108
61
|
# 3. Edit messages/en.json with real strings, then push.
|
|
109
62
|
```
|
|
110
63
|
|
|
111
|
-
Push → GitHub Action runs → bot commits `messages/<locale>.json` translations + cost summary on the PR.
|
|
112
|
-
|
|
113
64
|
## Other commands
|
|
114
65
|
|
|
115
66
|
```bash
|
|
@@ -125,11 +76,11 @@ npx autoglot --help # full flag list
|
|
|
125
76
|
|
|
126
77
|
### Monorepo
|
|
127
78
|
|
|
128
|
-
|
|
79
|
+
Keep `translate.config.json` next to each app’s catalog. Translation, `add`, and `doctor` look for the config in the current directory and its parents. To select an app from the repository root, pass `--config=apps/mobile/translate.config.json`. Paths inside the config are relative to the config file. Keep GitHub workflows in the repository root’s `.github/workflows/` directory.
|
|
129
80
|
|
|
130
81
|
## Quickstart — GitHub Action (manual setup)
|
|
131
82
|
|
|
132
|
-
|
|
83
|
+
Copy this workflow to `.github/workflows/translate.yml` to set up the Action by hand.
|
|
133
84
|
|
|
134
85
|
```yaml
|
|
135
86
|
# .github/workflows/translate.yml
|
|
@@ -162,7 +113,7 @@ Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json`, create
|
|
|
162
113
|
|
|
163
114
|
### Want it to run on pull requests instead?
|
|
164
115
|
|
|
165
|
-
Switch the trigger to `pull_request` and tell `actions/checkout` to use the PR's source branch
|
|
116
|
+
Switch the trigger to `pull_request` and tell `actions/checkout` to use the PR's source branch. The job below runs on pull requests from branches in the same repository.
|
|
166
117
|
|
|
167
118
|
```yaml
|
|
168
119
|
on:
|
|
@@ -173,6 +124,7 @@ on:
|
|
|
173
124
|
jobs:
|
|
174
125
|
translate:
|
|
175
126
|
runs-on: ubuntu-latest
|
|
127
|
+
if: github.event.pull_request.head.repo.full_name == github.repository
|
|
176
128
|
permissions:
|
|
177
129
|
contents: write
|
|
178
130
|
pull-requests: write
|
|
@@ -191,7 +143,8 @@ The action detects pull_request events automatically and pushes translations to
|
|
|
191
143
|
|
|
192
144
|
```bash
|
|
193
145
|
npm install -D autoglot
|
|
194
|
-
|
|
146
|
+
npx autoglot --dry-run
|
|
147
|
+
npx autoglot # Set ANTHROPIC_API_KEY in your environment first
|
|
195
148
|
```
|
|
196
149
|
|
|
197
150
|
Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
|
|
@@ -240,13 +193,13 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
|
|
|
240
193
|
| `model` | `claude-haiku-4-5` | Anthropic model. Haiku is recommended; quality is excellent. |
|
|
241
194
|
| `glossary` | `[]` | Product/brand names the model must keep verbatim. |
|
|
242
195
|
| `namespaceContext` | `{}` | Hint the model about each top-level namespace. Improves quality. |
|
|
243
|
-
| `namespaces` | `{}` |
|
|
196
|
+
| `namespaces` | `{}` | Map namespaces to their target locale lists. Other namespaces go to all target locales. |
|
|
244
197
|
|
|
245
198
|
## CLI flags
|
|
246
199
|
|
|
247
200
|
```
|
|
248
|
-
--check
|
|
249
|
-
--dry-run
|
|
201
|
+
--check Exit 1 when translation updates are pending. No API call.
|
|
202
|
+
--dry-run Preview the translation plan without updating catalogs.
|
|
250
203
|
--quiet Suppress per-locale and per-chunk progress. CI keeps verbose logs.
|
|
251
204
|
--locales=de,fr Restrict run to specific locales.
|
|
252
205
|
--model=<id> Override the configured model.
|
|
@@ -254,7 +207,8 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
|
|
|
254
207
|
--messages-dir=<path> Override config.messagesDir.
|
|
255
208
|
--lock-file=<path> Override config.lockFile.
|
|
256
209
|
--config=<path> Custom config file path.
|
|
257
|
-
--import-languine[=path] Seed
|
|
210
|
+
--import-languine[=path] Seed the lock file from languine.lock.
|
|
211
|
+
--summary-path=<path> Write the Markdown translation summary here.
|
|
258
212
|
-v, --version Print version and exit.
|
|
259
213
|
-h, --help Print help and exit.
|
|
260
214
|
```
|
|
@@ -263,31 +217,23 @@ Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
|
|
|
263
217
|
|
|
264
218
|
| Model | Cost (per 1M tokens) | When to use |
|
|
265
219
|
|---|---|---|
|
|
266
|
-
| `claude-haiku-4-5` *(default)* | $1 in / $5 out |
|
|
267
|
-
| `claude-sonnet-4-6` | $3 in / $15 out |
|
|
268
|
-
| `claude-opus-4-7` | $
|
|
220
|
+
| `claude-haiku-4-5` *(default)* | $1 in / $5 out | General translation |
|
|
221
|
+
| `claude-sonnet-4-6` | $3 in / $15 out | Copy that needs more nuance |
|
|
222
|
+
| `claude-opus-4-7` | $5 in / $25 out | Longer or more complex copy |
|
|
269
223
|
|
|
270
|
-
|
|
224
|
+
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.
|
|
271
225
|
|
|
272
226
|
## Migrating from Languine
|
|
273
227
|
|
|
274
228
|
```bash
|
|
275
229
|
npx autoglot --import-languine=languine.lock
|
|
276
|
-
|
|
230
|
+
npx autoglot --dry-run
|
|
277
231
|
```
|
|
278
232
|
|
|
279
|
-
|
|
233
|
+
Keep your existing locale files and review the dry-run output before replacing the Languine workflow. Missing translations and strings that changed since the imported hashes will appear in the plan.
|
|
280
234
|
|
|
281
235
|
## How it works
|
|
282
236
|
|
|
283
|
-
<!-- ARCHITECTURE DIAGRAM (optional)
|
|
284
|
-
File: .github/assets/how-it-works.svg
|
|
285
|
-
Prompt: "A simple horizontal flowchart with 5 boxes connected by arrows:
|
|
286
|
-
[en.json edit] → [diff vs lock file] → [Anthropic API: only changed keys]
|
|
287
|
-
→ [merge into <locale>.json files] → [bot commit + PR comment].
|
|
288
|
-
Monochrome dark theme, purple accent (#8b5cf6). Looks like a Linear
|
|
289
|
-
or Stripe docs diagram. Inter font."
|
|
290
|
-
-->
|
|
291
237
|
<p align="center">
|
|
292
238
|
<img src=".github/assets/how-it-works.svg" alt="autoglot architecture: diff → translate → merge → commit" width="1100">
|
|
293
239
|
</p>
|
|
@@ -313,7 +259,7 @@ Yes. `npx autoglot init` has explicit support for **Next.js (App Router & Pages
|
|
|
313
259
|
<details>
|
|
314
260
|
<summary><strong>What about ICU plurals, dates, gender?</strong></summary>
|
|
315
261
|
|
|
316
|
-
ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt to Claude. The placeholder validator covers `{name}` tokens;
|
|
262
|
+
ICU syntax (`{count, plural, one {# day} other {# days}}`) is preserved by the system prompt to Claude. The placeholder validator covers `{name}` tokens; ICU structure is handled by the model and should be reviewed in the resulting JSON.
|
|
317
263
|
|
|
318
264
|
</details>
|
|
319
265
|
|
|
@@ -327,14 +273,14 @@ JSON covers ~95% of JS app i18n. Adding YAML / `.strings` / Android XML triples
|
|
|
327
273
|
<details>
|
|
328
274
|
<summary><strong>Why not OpenAI / Gemini?</strong></summary>
|
|
329
275
|
|
|
330
|
-
|
|
276
|
+
The current release supports Anthropic. Follow the [roadmap](ROADMAP.md) for provider plans.
|
|
331
277
|
|
|
332
278
|
</details>
|
|
333
279
|
|
|
334
280
|
<details>
|
|
335
281
|
<summary><strong>Is the bot a "real" GitHub bot with an avatar?</strong></summary>
|
|
336
282
|
|
|
337
|
-
|
|
283
|
+
The Action writes commits as GitHub’s built-in `github-actions[bot]` account.
|
|
338
284
|
|
|
339
285
|
</details>
|
|
340
286
|
|
|
@@ -359,7 +305,7 @@ Add them to `glossary` in `translate.config.json`. They'll be passed to Claude w
|
|
|
359
305
|
- [ ] **v0.3** — YAML / `.strings` / Android XML formats (gated on demand)
|
|
360
306
|
- [ ] **v0.4** — Hosted GitHub App (real bot avatar, one-click install) — paid tier, OSS still first-class
|
|
361
307
|
|
|
362
|
-
See [
|
|
308
|
+
See the [roadmap](ROADMAP.md) for upcoming work and the [open issues](https://github.com/ffcabbar/autoglot/issues) for current maintenance tasks.
|
|
363
309
|
|
|
364
310
|
## Contributing
|
|
365
311
|
|
package/bin/cli.mjs
CHANGED
|
@@ -38,11 +38,13 @@ init flags
|
|
|
38
38
|
extract flags
|
|
39
39
|
--write Merge candidates into messages/en.json (existing
|
|
40
40
|
keys are never overwritten).
|
|
41
|
-
--source=<path> Override the
|
|
41
|
+
--source=<path> Override the configured source catalog.
|
|
42
|
+
--config=<path> Select an autoglot configuration.
|
|
43
|
+
--root=<path> Override the directory to scan.
|
|
42
44
|
|
|
43
45
|
Translation flags (when no subcommand given)
|
|
44
|
-
--check
|
|
45
|
-
--dry-run Show plan
|
|
46
|
+
--check Exit 1 if the lock or selected locales need updates.
|
|
47
|
+
--dry-run Show the plan without calling AI or updating translations.
|
|
46
48
|
--quiet Suppress per-locale progress (auto-disabled in CI).
|
|
47
49
|
--locales=de,fr Restrict run to specific locales.
|
|
48
50
|
--model=<id> Override the configured model (default: claude-haiku-4-5).
|
|
@@ -54,7 +56,7 @@ Translation flags (when no subcommand given)
|
|
|
54
56
|
--summary-path=<path> Where to write the markdown summary.
|
|
55
57
|
|
|
56
58
|
Environment
|
|
57
|
-
ANTHROPIC_API_KEY Required
|
|
59
|
+
ANTHROPIC_API_KEY Required when sending translation requests.
|
|
58
60
|
|
|
59
61
|
Docs
|
|
60
62
|
https://github.com/ffcabbar/autoglot
|
|
@@ -92,7 +94,7 @@ if (first === "doctor") {
|
|
|
92
94
|
if (first === "extract") {
|
|
93
95
|
const m = await import("./extract.mjs");
|
|
94
96
|
await m.run(argv.slice(1));
|
|
95
|
-
process.exit(0);
|
|
97
|
+
process.exit(process.exitCode ?? 0);
|
|
96
98
|
}
|
|
97
99
|
|
|
98
100
|
// Unknown subcommand sanity check: if first arg looks like a subcommand
|
package/bin/doctor.mjs
CHANGED
|
@@ -28,8 +28,10 @@ export async function run(argv = []) {
|
|
|
28
28
|
}
|
|
29
29
|
|
|
30
30
|
// 1. translate.config.json
|
|
31
|
-
if (paths.
|
|
31
|
+
if (paths.config) {
|
|
32
32
|
ok(`${relative(cwd, paths.configPath) || paths.configPath} found and parses.`);
|
|
33
|
+
} else if (args.config) {
|
|
34
|
+
e(`Configuration file ${args.config} not found.`);
|
|
33
35
|
} else {
|
|
34
36
|
w("translate.config.json not found — autoglot will use defaults. Consider `autoglot init`.");
|
|
35
37
|
}
|
package/bin/extract.mjs
CHANGED
|
@@ -9,13 +9,13 @@
|
|
|
9
9
|
// for "find me the obvious low-hanging strings" the regex approach
|
|
10
10
|
// catches ~80% of real strings with very few false positives.
|
|
11
11
|
|
|
12
|
-
import { readFileSync, writeFileSync,
|
|
13
|
-
import { join, relative,
|
|
12
|
+
import { readFileSync, writeFileSync, statSync, existsSync, mkdirSync } from "node:fs";
|
|
13
|
+
import { join, relative, resolve, dirname } from "node:path";
|
|
14
14
|
import { step, info, ok, warn, err, c } from "./prompts.mjs";
|
|
15
|
+
import { resolvePaths } from "./config.mjs";
|
|
15
16
|
import {
|
|
16
17
|
walk,
|
|
17
18
|
extractCandidates,
|
|
18
|
-
isLikelyUserFacing,
|
|
19
19
|
suggestKey,
|
|
20
20
|
setNested,
|
|
21
21
|
mergeKeys,
|
|
@@ -32,13 +32,26 @@ export const SKIP_DIRS = new Set([
|
|
|
32
32
|
* Parse `extract`-specific flags. Unknown flags are ignored (forward-compat).
|
|
33
33
|
*
|
|
34
34
|
* --write merge candidates into messages/en.json (skips existing keys)
|
|
35
|
-
* --source=<path> override the
|
|
35
|
+
* --source=<path> override the source catalog
|
|
36
|
+
* --config=<path> select an autoglot configuration
|
|
37
|
+
* --root=<path> override the directory to scan
|
|
36
38
|
*/
|
|
37
39
|
export function parseExtractArgs(argv) {
|
|
38
40
|
const opts = { write: false, source: null };
|
|
39
|
-
for (
|
|
41
|
+
for (let i = 0; i < argv.length; i++) {
|
|
42
|
+
const arg = argv[i];
|
|
40
43
|
if (arg === "--write") opts.write = true;
|
|
41
44
|
else if (arg.startsWith("--source=")) opts.source = arg.slice("--source=".length);
|
|
45
|
+
else if (arg.startsWith("--config=")) opts.config = arg.slice("--config=".length);
|
|
46
|
+
else if (arg.startsWith("--root=")) opts.root = arg.slice("--root=".length);
|
|
47
|
+
else if (arg === "--root") {
|
|
48
|
+
const next = argv[i + 1];
|
|
49
|
+
opts.root = "";
|
|
50
|
+
if (next && !next.startsWith("-")) {
|
|
51
|
+
opts.root = next;
|
|
52
|
+
i++;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
42
55
|
}
|
|
43
56
|
return opts;
|
|
44
57
|
}
|
|
@@ -48,11 +61,33 @@ export async function run(args = []) {
|
|
|
48
61
|
const cwd = process.cwd();
|
|
49
62
|
step("autoglot extract");
|
|
50
63
|
|
|
51
|
-
|
|
52
|
-
|
|
64
|
+
let paths;
|
|
65
|
+
try {
|
|
66
|
+
paths = resolvePaths(opts, cwd);
|
|
67
|
+
if (opts.config !== undefined && !paths.config) {
|
|
68
|
+
throw new Error(`Configuration file ${opts.config || "(empty path)"} not found.`);
|
|
69
|
+
}
|
|
70
|
+
} catch (error) {
|
|
71
|
+
err(error.message);
|
|
72
|
+
process.exitCode = 1;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const projectDir = paths.configPath ? dirname(paths.configPath) : cwd;
|
|
77
|
+
const target = relative(cwd, paths.source) || paths.source;
|
|
78
|
+
const isDirectory = (path) => statSync(path, { throwIfNoEntry: false })?.isDirectory();
|
|
79
|
+
const scanDirs = opts.root === undefined
|
|
80
|
+
? SCAN_DIRS.map((dir) => join(projectDir, dir))
|
|
81
|
+
: opts.root ? [resolve(cwd, opts.root)] : [];
|
|
82
|
+
const roots = scanDirs.filter(isDirectory);
|
|
53
83
|
if (roots.length === 0) {
|
|
54
|
-
|
|
55
|
-
|
|
84
|
+
if (opts.root !== undefined) {
|
|
85
|
+
err(`Scan directory ${opts.root || "(empty path)"} not found.`);
|
|
86
|
+
process.exitCode = 1;
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
warn(`No conventional source directory (${SCAN_DIRS.join(", ")}) found in ${projectDir}.`);
|
|
90
|
+
info("Pass --root <path> to scan a custom directory.");
|
|
56
91
|
return;
|
|
57
92
|
}
|
|
58
93
|
|
|
@@ -71,7 +106,7 @@ export async function run(args = []) {
|
|
|
71
106
|
}
|
|
72
107
|
const rel = relative(cwd, f);
|
|
73
108
|
for (const cand of extractCandidates(text)) {
|
|
74
|
-
const key = suggestKey(cand.text,
|
|
109
|
+
const key = suggestKey(cand.text, relative(projectDir, f));
|
|
75
110
|
allCandidates.push({ file: rel, line: cand.line, text: cand.text, key });
|
|
76
111
|
}
|
|
77
112
|
}
|
|
@@ -106,7 +141,7 @@ export async function run(args = []) {
|
|
|
106
141
|
}
|
|
107
142
|
|
|
108
143
|
if (!opts.write) {
|
|
109
|
-
step(
|
|
144
|
+
step(`Suggested additions to ${target}`);
|
|
110
145
|
process.stdout.write(JSON.stringify(merged, null, 2) + "\n");
|
|
111
146
|
}
|
|
112
147
|
|
|
@@ -114,20 +149,20 @@ export async function run(args = []) {
|
|
|
114
149
|
info(`Found ${c.bold}${allCandidates.length}${c.reset} candidate${allCandidates.length === 1 ? "" : "s"} across ${c.bold}${byFile.size}${c.reset} file${byFile.size === 1 ? "" : "s"}.`);
|
|
115
150
|
|
|
116
151
|
if (opts.write) {
|
|
117
|
-
const
|
|
118
|
-
const full = join(cwd, target);
|
|
152
|
+
const full = paths.source;
|
|
119
153
|
let existing = {};
|
|
120
154
|
if (existsSync(full)) {
|
|
121
155
|
try {
|
|
122
156
|
existing = JSON.parse(readFileSync(full, "utf8"));
|
|
123
157
|
} catch (e) {
|
|
124
158
|
err(`Couldn't parse ${target}: ${e.message}. Aborting --write.`);
|
|
159
|
+
process.exitCode = 1;
|
|
125
160
|
return;
|
|
126
161
|
}
|
|
127
162
|
}
|
|
128
163
|
const { merged: out, added, skipped, conflicts } = mergeKeys(existing, allCandidates);
|
|
129
164
|
|
|
130
|
-
step(
|
|
165
|
+
step(`Writing ${target}`);
|
|
131
166
|
mkdirSync(dirname(full), { recursive: true });
|
|
132
167
|
writeFileSync(full, JSON.stringify(out, null, 2) + "\n");
|
|
133
168
|
ok(`${target} now has ${added.length} new key${added.length === 1 ? "" : "s"}.`);
|
|
@@ -159,6 +194,6 @@ export async function run(args = []) {
|
|
|
159
194
|
}
|
|
160
195
|
|
|
161
196
|
step("Next");
|
|
162
|
-
info(`Review the candidates above. Copy the relevant ones into ${c.bold}
|
|
197
|
+
info(`Review the candidates above. Copy the relevant ones into ${c.bold}${target}${c.reset} (or re-run with ${c.bold}--write${c.reset} to do it automatically), then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
|
|
163
198
|
info("Default mode is read-only. Use --write to merge into messages/en.json (existing keys are never overwritten).");
|
|
164
199
|
}
|
package/bin/helpers.mjs
CHANGED
|
@@ -92,7 +92,7 @@ export function parseLockYaml(raw, defaultSource = "") {
|
|
|
92
92
|
if (m) { lock.source = m[1]; continue; }
|
|
93
93
|
if (/^hashes:\s*$/.test(line)) { inHashes = true; continue; }
|
|
94
94
|
} else {
|
|
95
|
-
const m = line.match(/^\s{2}(
|
|
95
|
+
const m = line.match(/^\s{2}(.+):\s*(\S+)\s*$/);
|
|
96
96
|
if (m) lock.hashes[m[1]] = m[2];
|
|
97
97
|
else if (!/^\s/.test(line)) inHashes = false;
|
|
98
98
|
}
|
|
@@ -111,7 +111,7 @@ export function dumpLockYaml(lock) {
|
|
|
111
111
|
export function allowedTopLevelNamespaces(source, locale, cfg) {
|
|
112
112
|
const out = new Set();
|
|
113
113
|
for (const ns of Object.keys(source)) {
|
|
114
|
-
const restriction = cfg.namespaces?.[ns];
|
|
114
|
+
const restriction = cfg.namespaces?.[ns] ?? cfg.namespaces?.[ns.split(".")[0]];
|
|
115
115
|
if (!restriction || restriction.includes(locale)) out.add(ns);
|
|
116
116
|
}
|
|
117
117
|
return out;
|
package/bin/translate.mjs
CHANGED
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
// --import-languine[=<path>] Import a languine.lock to seed our lock file.
|
|
32
32
|
|
|
33
33
|
import { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from "node:fs";
|
|
34
|
-
import { join, resolve,
|
|
34
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
35
35
|
import { tmpdir } from "node:os";
|
|
36
36
|
import {
|
|
37
37
|
parseArgs,
|
|
@@ -56,8 +56,8 @@ Usage
|
|
|
56
56
|
npx autoglot [flags]
|
|
57
57
|
|
|
58
58
|
Flags
|
|
59
|
-
--check
|
|
60
|
-
--dry-run Show plan
|
|
59
|
+
--check Exit 1 if the lock or selected locales need updates.
|
|
60
|
+
--dry-run Show the plan without calling AI or updating translations.
|
|
61
61
|
--quiet Suppress per-locale progress (auto-disabled in CI).
|
|
62
62
|
--locales=de,fr Restrict run to specific locales.
|
|
63
63
|
--model=<id> Override the configured model (default: claude-haiku-4-5).
|
|
@@ -71,7 +71,7 @@ Flags
|
|
|
71
71
|
-h, --help Print this help and exit.
|
|
72
72
|
|
|
73
73
|
Environment
|
|
74
|
-
ANTHROPIC_API_KEY Required
|
|
74
|
+
ANTHROPIC_API_KEY Required when sending translation requests.
|
|
75
75
|
|
|
76
76
|
Docs
|
|
77
77
|
https://github.com/ffcabbar/autoglot
|
|
@@ -85,7 +85,7 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
85
85
|
const PRICING = {
|
|
86
86
|
"claude-haiku-4-5": { input: 1.0, output: 5.0 },
|
|
87
87
|
"claude-sonnet-4-6": { input: 3.0, output: 15.0 },
|
|
88
|
-
"claude-opus-4-7": { input:
|
|
88
|
+
"claude-opus-4-7": { input: 5.0, output: 25.0 },
|
|
89
89
|
};
|
|
90
90
|
|
|
91
91
|
const LOCALE_DISPLAY = new Intl.DisplayNames(["en"], { type: "language" });
|
|
@@ -117,6 +117,7 @@ const config = __paths.config || { namespaces: {} };
|
|
|
117
117
|
const SOURCE_FILE = __paths.source;
|
|
118
118
|
const MESSAGES_DIR = __paths.messagesDir;
|
|
119
119
|
const LOCK_FILE = __paths.lockFile;
|
|
120
|
+
const LOCK_SOURCE = relative(dirname(LOCK_FILE), SOURCE_FILE).split(sep).join("/");
|
|
120
121
|
const SUMMARY_FILE = args["summary-path"]
|
|
121
122
|
? resolvePath(args["summary-path"])
|
|
122
123
|
: join(tmpdir(), "translate-summary.md");
|
|
@@ -154,17 +155,48 @@ async function run() {
|
|
|
154
155
|
const source = readJSON(SOURCE_FILE);
|
|
155
156
|
const sourceFlat = flatten(source);
|
|
156
157
|
const lock = loadLock();
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
158
|
+
const discovered = discoverTargetLocales();
|
|
159
|
+
const targets = args.locales === undefined
|
|
160
|
+
? discovered
|
|
161
|
+
: typeof args.locales === "string"
|
|
162
|
+
? [...new Set(args.locales.split(",").map((s) => s.trim()).filter(Boolean))]
|
|
163
|
+
: [];
|
|
164
|
+
if (args.locales !== undefined && targets.length === 0) {
|
|
165
|
+
console.error("[translate] --locales requires a comma-separated list of target locale codes.");
|
|
166
|
+
process.exit(1);
|
|
167
|
+
}
|
|
168
|
+
for (const locale of targets) {
|
|
169
|
+
try {
|
|
170
|
+
if (join(MESSAGES_DIR, `${locale}.json`).toLowerCase() === SOURCE_FILE.toLowerCase()) {
|
|
171
|
+
throw new Error("matches the source file");
|
|
172
|
+
}
|
|
173
|
+
Intl.getCanonicalLocales(locale);
|
|
174
|
+
} catch {
|
|
175
|
+
console.error(`[translate] Invalid target locale '${locale}'. Use a locale code different from the source locale file.`);
|
|
176
|
+
process.exit(1);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
160
179
|
|
|
161
180
|
const newDelta = [];
|
|
162
181
|
const changedDelta = [];
|
|
163
182
|
for (const key of Object.keys(sourceFlat)) {
|
|
164
183
|
const h = hash(sourceFlat[key]);
|
|
165
|
-
if (!lock.hashes
|
|
184
|
+
if (!Object.hasOwn(lock.hashes, key)) newDelta.push(key);
|
|
166
185
|
else if (lock.hashes[key] !== h) changedDelta.push(key);
|
|
167
186
|
}
|
|
187
|
+
const delta = new Set([...newDelta, ...changedDelta]);
|
|
188
|
+
const removed = Object.keys(lock.hashes).filter((key) => !Object.hasOwn(sourceFlat, key));
|
|
189
|
+
const plans = targets.map((locale) => {
|
|
190
|
+
const targetPath = join(MESSAGES_DIR, `${locale}.json`);
|
|
191
|
+
const existing = existsSync(targetPath) ? readJSON(targetPath) : {};
|
|
192
|
+
const existingFlat = flatten(existing);
|
|
193
|
+
const allowed = allowedTopLevelNamespaces(source, locale, config);
|
|
194
|
+
const filteredSource = pickAllowedSource(source, allowed);
|
|
195
|
+
const allowedFlat = flatten(filteredSource);
|
|
196
|
+
const keysToTranslate = Object.keys(allowedFlat).filter((key) => delta.has(key) || !Object.hasOwn(existingFlat, key));
|
|
197
|
+
const hasOrphans = Object.keys(existingFlat).some((key) => !Object.hasOwn(allowedFlat, key));
|
|
198
|
+
return { locale, targetPath, existing, filteredSource, keysToTranslate, hasOrphans };
|
|
199
|
+
});
|
|
168
200
|
|
|
169
201
|
console.log(`[translate] source: ${newDelta.length} new keys, ${changedDelta.length} modified (${newDelta.length + changedDelta.length} total delta)`);
|
|
170
202
|
if (targets.length === 0) {
|
|
@@ -172,20 +204,24 @@ async function run() {
|
|
|
172
204
|
}
|
|
173
205
|
|
|
174
206
|
if (args.check) {
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
|
|
207
|
+
if (delta.size > 0) console.log("[translate] Delta keys:", [...delta].join(", "));
|
|
208
|
+
if (removed.length > 0) console.log("[translate] Removed source keys:", removed.join(", "));
|
|
209
|
+
const pending = plans.filter(({ keysToTranslate, hasOrphans }) => keysToTranslate.length || hasOrphans);
|
|
210
|
+
if (pending.length > 0) {
|
|
211
|
+
console.log("[translate] Locales needing updates:", pending.map(({ locale }) => locale).join(", "));
|
|
178
212
|
}
|
|
179
|
-
|
|
180
|
-
|
|
213
|
+
if (delta.size || removed.length || pending.length) process.exit(1);
|
|
214
|
+
console.log("[translate] All selected locales up to date.");
|
|
215
|
+
return;
|
|
181
216
|
}
|
|
182
217
|
|
|
183
|
-
|
|
218
|
+
const dryRun = Boolean(args["dry-run"]);
|
|
219
|
+
if (!dryRun && plans.some(({ keysToTranslate }) => keysToTranslate.length) && !process.env.ANTHROPIC_API_KEY) {
|
|
184
220
|
console.error("[translate] ANTHROPIC_API_KEY is not set.");
|
|
185
221
|
process.exit(1);
|
|
186
222
|
}
|
|
187
223
|
|
|
188
|
-
if (!
|
|
224
|
+
if (!dryRun && targets.length) mkdirSync(MESSAGES_DIR, { recursive: true });
|
|
189
225
|
|
|
190
226
|
// Per-locale work runs in parallel up to LOCALE_CONCURRENCY. Each locale
|
|
191
227
|
// writes its own file, so there's no contention. Aggregation into
|
|
@@ -195,28 +231,14 @@ async function run() {
|
|
|
195
231
|
let totalIn = 0, totalOut = 0, totalCost = 0, skipped = 0;
|
|
196
232
|
const limit = pLimit(LOCALE_CONCURRENCY);
|
|
197
233
|
|
|
198
|
-
async function processLocale(locale) {
|
|
199
|
-
const targetPath = join(MESSAGES_DIR, `${locale}.json`);
|
|
200
|
-
const existing = existsSync(targetPath) ? readJSON(targetPath) : {};
|
|
201
|
-
const existingFlat = flatten(existing);
|
|
202
|
-
|
|
203
|
-
const allowedNs = allowedTopLevelNamespaces(source, locale, config);
|
|
204
|
-
const isAllowed = (k) => allowedNs.has(k.split(".")[0]);
|
|
205
|
-
|
|
206
|
-
const missing = Object.keys(sourceFlat).filter((k) => isAllowed(k) && !(k in existingFlat));
|
|
207
|
-
const delta = [...newDelta, ...changedDelta].filter(isAllowed);
|
|
208
|
-
const keysToTranslate = Array.from(new Set([...missing, ...delta]));
|
|
209
|
-
|
|
210
|
-
const filteredSource = pickAllowedSource(source, allowedNs);
|
|
211
|
-
const hasOrphans = Object.keys(existingFlat).some((k) => !(k in sourceFlat) || !isAllowed(k));
|
|
212
|
-
|
|
234
|
+
async function processLocale({ locale, targetPath, existing, filteredSource, keysToTranslate, hasOrphans }) {
|
|
213
235
|
if (keysToTranslate.length === 0) {
|
|
214
236
|
if (!hasOrphans) {
|
|
215
237
|
verbose(`[translate] ${locale.padEnd(6)} → up to date (skipped)`);
|
|
216
238
|
skipped++;
|
|
217
239
|
return;
|
|
218
240
|
}
|
|
219
|
-
if (
|
|
241
|
+
if (dryRun) {
|
|
220
242
|
verbose(`[translate] ${locale.padEnd(6)} → would remove orphan keys (dry-run)`);
|
|
221
243
|
perLocale.push({ locale, keys: 0, inTok: 0, outTok: 0, cost: 0 });
|
|
222
244
|
return;
|
|
@@ -228,7 +250,7 @@ async function run() {
|
|
|
228
250
|
return;
|
|
229
251
|
}
|
|
230
252
|
|
|
231
|
-
if (
|
|
253
|
+
if (dryRun) {
|
|
232
254
|
verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys (dry-run)`);
|
|
233
255
|
perLocale.push({ locale, keys: keysToTranslate.length, inTok: 0, outTok: 0, cost: 0 });
|
|
234
256
|
return;
|
|
@@ -259,14 +281,27 @@ async function run() {
|
|
|
259
281
|
verbose(`[translate] ${locale.padEnd(6)} → ${keysToTranslate.length} keys | in: ${usageIn} out: ${usageOut} | $${cost.toFixed(5)}`);
|
|
260
282
|
}
|
|
261
283
|
|
|
262
|
-
await Promise.all(
|
|
284
|
+
await Promise.all(plans.map((plan) => limit(() => processLocale(plan))));
|
|
263
285
|
// Sort perLocale alphabetically so the summary table is stable across runs
|
|
264
286
|
// (parallel completion order would otherwise scramble it).
|
|
265
287
|
perLocale.sort((a, b) => a.locale.localeCompare(b.locale));
|
|
266
288
|
|
|
267
|
-
if (!
|
|
268
|
-
|
|
269
|
-
|
|
289
|
+
if (!dryRun) {
|
|
290
|
+
// A shared hash can only advance after every applicable existing locale has caught up.
|
|
291
|
+
const selected = new Set(targets);
|
|
292
|
+
const pending = new Set();
|
|
293
|
+
for (const locale of discovered.filter((locale) => !selected.has(locale))) {
|
|
294
|
+
const allowed = allowedTopLevelNamespaces(source, locale, config);
|
|
295
|
+
for (const key of Object.keys(flatten(pickAllowedSource(source, allowed)))) pending.add(key);
|
|
296
|
+
}
|
|
297
|
+
if (targets.length > 0) {
|
|
298
|
+
for (const key of Object.keys(sourceFlat)) {
|
|
299
|
+
if (!pending.has(key)) lock.hashes[key] = hash(sourceFlat[key]);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
for (const key of removed) delete lock.hashes[key];
|
|
303
|
+
lock.source = LOCK_SOURCE;
|
|
304
|
+
mkdirSync(dirname(LOCK_FILE), { recursive: true });
|
|
270
305
|
writeFileSync(LOCK_FILE, dumpLockYaml(lock));
|
|
271
306
|
}
|
|
272
307
|
|
|
@@ -278,14 +313,14 @@ async function run() {
|
|
|
278
313
|
totalOut,
|
|
279
314
|
totalCost,
|
|
280
315
|
perLocale,
|
|
281
|
-
dryRun
|
|
316
|
+
dryRun,
|
|
282
317
|
newKeys: newDelta.length,
|
|
283
318
|
modifiedKeys: changedDelta.length,
|
|
284
319
|
});
|
|
285
320
|
console.log("[translate] ──────────────────────────────────────");
|
|
286
321
|
console.log(summary.stdout);
|
|
287
|
-
if (STEP_SUMMARY) writeFileSync(STEP_SUMMARY, summary.markdown, { flag: "a" });
|
|
288
|
-
writeFileSync(SUMMARY_FILE, summary.markdown);
|
|
322
|
+
if (STEP_SUMMARY && !dryRun) writeFileSync(STEP_SUMMARY, summary.markdown, { flag: "a" });
|
|
323
|
+
if (!dryRun || args["summary-path"]) writeFileSync(SUMMARY_FILE, summary.markdown);
|
|
289
324
|
}
|
|
290
325
|
|
|
291
326
|
// --- Anthropic call -------------------------------------------------------
|
|
@@ -293,8 +328,12 @@ async function run() {
|
|
|
293
328
|
// format with unescaped characters — the API returns `input` as a pre-parsed
|
|
294
329
|
// object, eliminating a whole class of JSON parse failures (e.g. a Lithuanian
|
|
295
330
|
// translation closing a quoted word with ASCII " instead of U+201D).
|
|
296
|
-
async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
|
|
331
|
+
async function translate(locale, payload, attempt = 1, rateAttempt = 0, usage = { input_tokens: 0, output_tokens: 0 }) {
|
|
297
332
|
const localeName = LOCALE_DISPLAY.of(locale) || locale;
|
|
333
|
+
let sourceLanguage = "the source language";
|
|
334
|
+
try {
|
|
335
|
+
sourceLanguage = LOCALE_DISPLAY.of(basename(SOURCE_FILE, ".json"));
|
|
336
|
+
} catch { /* the source file can have a name other than a locale code */ }
|
|
298
337
|
const namespaces = new Set(Object.keys(payload).map((k) => k.split(".")[0]));
|
|
299
338
|
const nsCtx = [...namespaces]
|
|
300
339
|
.map((n) => `- ${n}: ${(config.namespaceContext && config.namespaceContext[n]) || "application copy"}`)
|
|
@@ -304,7 +343,7 @@ async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
|
|
|
304
343
|
? ` Keep these product names verbatim: ${config.glossary.join(", ")}.`
|
|
305
344
|
: "";
|
|
306
345
|
|
|
307
|
-
const system = `You are a professional localization engineer. Translate
|
|
346
|
+
const system = `You are a professional localization engineer. Translate values from ${sourceLanguage} 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). Preserve line breaks as actual newline characters, not literal backslash-n sequences.${glossary} Call the emit_translations tool with every input key mapped to its translated string — do not write prose outside the tool call.`;
|
|
308
347
|
|
|
309
348
|
const user = `Target locale: ${localeName} (${locale}).\nNamespace context:\n${nsCtx}\n\nTranslate:\n${JSON.stringify(payload, null, 2)}`;
|
|
310
349
|
|
|
@@ -338,36 +377,42 @@ async function translate(locale, payload, attempt = 1, rateAttempt = 0) {
|
|
|
338
377
|
const retryAfterSec = Number(res.headers.get("retry-after")) || 60;
|
|
339
378
|
console.warn(`[translate] ${locale}: rate limited (429), sleeping ${retryAfterSec}s (retry ${rateAttempt + 1}/${RATE_LIMIT_MAX_RETRIES})`);
|
|
340
379
|
await sleep(retryAfterSec * 1000 + 500);
|
|
341
|
-
return translate(locale, payload, attempt, rateAttempt + 1);
|
|
380
|
+
return translate(locale, payload, attempt, rateAttempt + 1, usage);
|
|
342
381
|
}
|
|
343
382
|
throw new Error(`Anthropic API ${res.status}: ${await res.text()}`);
|
|
344
383
|
}
|
|
345
384
|
|
|
346
385
|
const body = await res.json();
|
|
347
|
-
|
|
386
|
+
usage.input_tokens += body.usage?.input_tokens ?? 0;
|
|
387
|
+
usage.output_tokens += body.usage?.output_tokens ?? 0;
|
|
388
|
+
const toolUse = body.content?.find((c) => c.type === "tool_use" && c.name === "emit_translations");
|
|
348
389
|
if (!toolUse || typeof toolUse.input !== "object" || toolUse.input === null) {
|
|
349
390
|
if (attempt >= 2) throw new Error(`${locale}: no tool_use block in response\nRaw:\n${JSON.stringify(body.content)}`);
|
|
350
391
|
console.warn(`[translate] ${locale} → missing tool_use block, retrying once`);
|
|
351
|
-
return translate(locale, payload, attempt + 1);
|
|
392
|
+
return translate(locale, payload, attempt + 1, rateAttempt, usage);
|
|
352
393
|
}
|
|
353
394
|
const translations = toolUse.input;
|
|
354
395
|
|
|
355
396
|
for (const key of Object.keys(payload)) {
|
|
356
|
-
if (typeof translations[key] !== "string") {
|
|
357
|
-
if (attempt < 2) return translate(locale, payload, attempt + 1);
|
|
358
|
-
|
|
359
|
-
translations[key] = payload[key];
|
|
360
|
-
continue;
|
|
397
|
+
if (!Object.hasOwn(translations, key) || typeof translations[key] !== "string") {
|
|
398
|
+
if (attempt < 2) return translate(locale, payload, attempt + 1, rateAttempt, usage);
|
|
399
|
+
throw new Error(`${locale}: model omitted a translation for '${key}'`);
|
|
361
400
|
}
|
|
362
401
|
const srcP = extractPlaceholders(payload[key]);
|
|
363
402
|
const outP = extractPlaceholders(translations[key]);
|
|
364
403
|
if (!setsEqual(srcP, outP)) {
|
|
365
404
|
if (attempt >= 2) throw new Error(`${locale}: placeholder mismatch on '${key}'. source=[${[...srcP].join(",")}] got=[${[...outP].join(",")}]`);
|
|
366
|
-
return translate(locale, payload, attempt + 1);
|
|
405
|
+
return translate(locale, payload, attempt + 1, rateAttempt, usage);
|
|
406
|
+
}
|
|
407
|
+
const sourceBreaks = String(payload[key]).match(/\n/g)?.length ?? 0;
|
|
408
|
+
const translatedBreaks = translations[key].match(/\n/g)?.length ?? 0;
|
|
409
|
+
if (sourceBreaks > 0 && sourceBreaks !== translatedBreaks) {
|
|
410
|
+
if (attempt < 2) return translate(locale, payload, attempt + 1, rateAttempt, usage);
|
|
411
|
+
throw new Error(`${locale}: newline mismatch on '${key}'`);
|
|
367
412
|
}
|
|
368
413
|
}
|
|
369
414
|
|
|
370
|
-
return { translations,
|
|
415
|
+
return { translations: Object.fromEntries(Object.keys(payload).map((key) => [key, translations[key]])), usage };
|
|
371
416
|
}
|
|
372
417
|
|
|
373
418
|
// --- Helpers --------------------------------------------------------------
|
|
@@ -380,8 +425,8 @@ function readJSON(p) {
|
|
|
380
425
|
}
|
|
381
426
|
|
|
382
427
|
function loadLock() {
|
|
383
|
-
if (!existsSync(LOCK_FILE)) return { version: 1, source:
|
|
384
|
-
return parseLockYaml(readFileSync(LOCK_FILE, "utf8"),
|
|
428
|
+
if (!existsSync(LOCK_FILE)) return { version: 1, source: LOCK_SOURCE, hashes: {} };
|
|
429
|
+
return parseLockYaml(readFileSync(LOCK_FILE, "utf8"), LOCK_SOURCE);
|
|
385
430
|
}
|
|
386
431
|
|
|
387
432
|
// loadConfig moved to ./config.mjs (shared with add/doctor; resolves
|
|
@@ -389,7 +434,7 @@ function loadLock() {
|
|
|
389
434
|
|
|
390
435
|
function discoverTargetLocales() {
|
|
391
436
|
if (!existsSync(MESSAGES_DIR)) return [];
|
|
392
|
-
const sourceBasename = SOURCE_FILE
|
|
437
|
+
const sourceBasename = basename(SOURCE_FILE);
|
|
393
438
|
return readdirSync(MESSAGES_DIR)
|
|
394
439
|
.filter((f) => f.endsWith(".json") && f !== sourceBasename)
|
|
395
440
|
.map((f) => f.slice(0, -5))
|
|
@@ -403,16 +448,29 @@ function importLanguineLock(srcPath) {
|
|
|
403
448
|
}
|
|
404
449
|
const raw = readFileSync(srcPath, "utf8");
|
|
405
450
|
const hashes = {};
|
|
451
|
+
let inFiles = false;
|
|
406
452
|
let inFile = false;
|
|
453
|
+
let matchedFile = false;
|
|
407
454
|
for (const line of raw.split("\n")) {
|
|
408
|
-
if (/^files
|
|
409
|
-
if (/^\
|
|
410
|
-
if (
|
|
455
|
+
if (/^files:\s*$/.test(line)) { inFiles = true; continue; }
|
|
456
|
+
if (/^\S/.test(line)) inFiles = false;
|
|
457
|
+
if (!inFiles) continue;
|
|
458
|
+
const file = line.match(/^ {2}(\S.*\.json):\s*$/)?.[1];
|
|
459
|
+
if (/^ {2}\S/.test(line)) {
|
|
460
|
+
inFile = Boolean(file) && [dirname(srcPath), CWD].some((base) => resolve(base, file) === SOURCE_FILE);
|
|
461
|
+
matchedFile ||= inFile;
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
411
464
|
if (!inFile) continue;
|
|
412
|
-
const m = line.match(
|
|
413
|
-
if (m) hashes[m[1].trim()] = m[2].
|
|
465
|
+
const m = line.match(/^ {4}(.+):\s*([0-9a-f]{32})\s*$/i);
|
|
466
|
+
if (m) hashes[m[1].trim().replaceAll("\\.", ".")] = m[2].toLowerCase();
|
|
467
|
+
}
|
|
468
|
+
if (!matchedFile) {
|
|
469
|
+
console.error(`[translate] No entry in ${srcPath} matches ${SOURCE_FILE}. Check --source or --config.`);
|
|
470
|
+
process.exit(1);
|
|
414
471
|
}
|
|
415
|
-
const lock = { version: 1, source:
|
|
472
|
+
const lock = { version: 1, source: LOCK_SOURCE, hashes };
|
|
473
|
+
mkdirSync(dirname(LOCK_FILE), { recursive: true });
|
|
416
474
|
writeFileSync(LOCK_FILE, dumpLockYaml(lock));
|
|
417
475
|
console.log(`[translate] Imported ${Object.keys(hashes).length} hashes from ${srcPath} → ${LOCK_FILE}`);
|
|
418
476
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "autoglot",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.4",
|
|
4
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
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
],
|
|
14
14
|
"scripts": {
|
|
15
15
|
"translate": "node bin/translate.mjs",
|
|
16
|
-
"test": "node --test tests/helpers.test.mjs tests/detect.test.mjs tests/templates.test.mjs tests/extract.test.mjs tests/pm.test.mjs tests/init-args.test.mjs tests/expo.test.mjs tests/config.test.mjs"
|
|
16
|
+
"test": "node --test tests/helpers.test.mjs tests/detect.test.mjs tests/templates.test.mjs tests/extract.test.mjs tests/pm.test.mjs tests/init-args.test.mjs tests/expo.test.mjs tests/config.test.mjs tests/translation.test.mjs"
|
|
17
17
|
},
|
|
18
18
|
"keywords": [
|
|
19
19
|
"i18n",
|