autoglot 0.1.0 → 0.2.2
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 +58 -14
- package/bin/add.mjs +63 -0
- package/bin/cli.mjs +98 -0
- package/bin/detect.mjs +94 -0
- package/bin/doctor.mjs +119 -0
- package/bin/extract-helpers.mjs +195 -0
- package/bin/extract.mjs +100 -0
- package/bin/init.mjs +203 -0
- package/bin/prompts.mjs +145 -0
- package/bin/templates/common.mjs +72 -0
- package/bin/templates/nextjs-app-router.mjs +135 -0
- package/bin/templates/nextjs-pages-router.mjs +26 -0
- package/bin/templates/react-native.mjs +62 -0
- package/bin/templates/vite-react.mjs +52 -0
- package/bin/templates/vue-i18n.mjs +51 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -68,7 +68,60 @@ It is **not** a runtime i18n library. You still need [`next-intl`](https://next-
|
|
|
68
68
|
<img src=".github/assets/pr-comment.svg" alt="The bot posts a cost summary as a PR comment" width="720">
|
|
69
69
|
</p>
|
|
70
70
|
|
|
71
|
-
## Quickstart (
|
|
71
|
+
## Quickstart — `npx autoglot init` (30 seconds)
|
|
72
|
+
|
|
73
|
+
Inside any project:
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npx autoglot init
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
That's it. The CLI:
|
|
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)
|
|
85
|
+
|
|
86
|
+
### Supported frameworks
|
|
87
|
+
|
|
88
|
+
| Framework | Runtime library | What `init` scaffolds |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| **Next.js (App Router)** | `next-intl` | `src/i18n/routing.ts`, `src/i18n/request.ts`, `src/middleware.ts`, plus a starter `src/app/[locale]/layout.tsx` + `page.tsx` if no `[locale]` segment exists |
|
|
91
|
+
| **Next.js (Pages Router)** | `next-i18next` | Messages + workflow only; prints precise wiring steps (next.config.js i18n block, `appWithTranslation` HOC, `serverSideTranslations` in pages) |
|
|
92
|
+
| **React Native** | `i18next` + `react-i18next` | `src/i18n/index.ts` with all locales registered |
|
|
93
|
+
| **Vite + React** | `i18next` + `react-i18next` | `src/i18n.ts` |
|
|
94
|
+
| **Vue / Nuxt** | `vue-i18n` | `src/i18n.ts` (Composition API mode) |
|
|
95
|
+
| **Generic / unknown** | (your choice) | Messages + workflow only — pair with any i18n library that reads JSON |
|
|
96
|
+
|
|
97
|
+
After init, three things to finish:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
# 1. Install the runtime i18n library it suggested (e.g. next-intl, react-i18next)
|
|
101
|
+
npm install next-intl
|
|
102
|
+
|
|
103
|
+
# 2. Add your Anthropic API key as a repo secret
|
|
104
|
+
gh secret set ANTHROPIC_API_KEY
|
|
105
|
+
|
|
106
|
+
# 3. Edit messages/en.json with real strings, then push.
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Push → GitHub Action runs → bot commits `messages/<locale>.json` translations + cost summary on the PR.
|
|
110
|
+
|
|
111
|
+
## Other commands
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
npx autoglot # run translation (the default; same as before)
|
|
115
|
+
npx autoglot init # interactive scaffold (above)
|
|
116
|
+
npx autoglot add tr ja zh # add new target locales (creates empty JSON files)
|
|
117
|
+
npx autoglot doctor # health check the setup
|
|
118
|
+
npx autoglot extract # scan source for hardcoded strings and suggest keys
|
|
119
|
+
npx autoglot --help # full flag list
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Quickstart — GitHub Action (manual setup)
|
|
123
|
+
|
|
124
|
+
If you'd rather skip `init` and write the workflow yourself:
|
|
72
125
|
|
|
73
126
|
```yaml
|
|
74
127
|
# .github/workflows/translate.yml
|
|
@@ -97,25 +150,16 @@ jobs:
|
|
|
97
150
|
anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
|
|
98
151
|
```
|
|
99
152
|
|
|
100
|
-
Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json
|
|
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.
|
|
153
|
+
Add `ANTHROPIC_API_KEY` to your repo secrets, drop a `messages/en.json`, create one empty `messages/<locale>.json` per language. On every push the bot will diff, translate, commit the diff back, and post a cost summary.
|
|
106
154
|
|
|
107
|
-
## Quickstart
|
|
155
|
+
## Quickstart — CLI (no GitHub)
|
|
108
156
|
|
|
109
157
|
```bash
|
|
110
158
|
npm install -D autoglot
|
|
111
|
-
echo '{ "greeting": "Hello, world!" }' > messages/en.json
|
|
112
|
-
echo '{}' > messages/es.json
|
|
113
|
-
echo '{}' > messages/de.json
|
|
114
|
-
|
|
115
159
|
ANTHROPIC_API_KEY=sk-ant-... npx autoglot
|
|
116
160
|
```
|
|
117
161
|
|
|
118
|
-
|
|
162
|
+
Works in any CI (GitLab, CircleCI, Jenkins) or on your laptop.
|
|
119
163
|
|
|
120
164
|
## vs. the alternatives
|
|
121
165
|
|
|
@@ -227,7 +271,7 @@ In CI, the action then commits the diff and posts the cost summary on the PR.
|
|
|
227
271
|
<details>
|
|
228
272
|
<summary><strong>Does it work with my framework?</strong></summary>
|
|
229
273
|
|
|
230
|
-
|
|
274
|
+
Yes. `npx autoglot init` has explicit support for **Next.js (App Router & Pages Router)**, **React Native**, **Vite + React**, and **Vue / Nuxt** — it scaffolds the right runtime setup for each. For anything else (Astro, SvelteKit, Solid, plain HTML, native mobile, server-side, ...) `init` runs in generic mode and just creates the messages + workflow; pair with whichever i18n library you already use that reads JSON.
|
|
231
275
|
|
|
232
276
|
</details>
|
|
233
277
|
|
package/bin/add.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// `autoglot add <locale> [<locale>...]` — add new target locales.
|
|
2
|
+
//
|
|
3
|
+
// Creates an empty messages/<locale>.json. The next push to en.json will
|
|
4
|
+
// populate it. Idempotent: if the file already exists, we leave it alone.
|
|
5
|
+
|
|
6
|
+
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { info, ok, warn, err, step, c } from "./prompts.mjs";
|
|
9
|
+
|
|
10
|
+
export async function run(args) {
|
|
11
|
+
const positional = args.filter((a) => !a.startsWith("-"));
|
|
12
|
+
if (positional.length === 0) {
|
|
13
|
+
err("Usage: autoglot add <locale> [<locale>...]");
|
|
14
|
+
err('Example: autoglot add tr ja zh');
|
|
15
|
+
process.exit(1);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const cwd = process.cwd();
|
|
19
|
+
step("autoglot add");
|
|
20
|
+
|
|
21
|
+
// Try to read messagesDir from translate.config.json
|
|
22
|
+
let messagesDir = "messages";
|
|
23
|
+
const cfgPath = join(cwd, "translate.config.json");
|
|
24
|
+
if (existsSync(cfgPath)) {
|
|
25
|
+
try {
|
|
26
|
+
const cfg = JSON.parse(readFileSync(cfgPath, "utf8"));
|
|
27
|
+
if (cfg.messagesDir) messagesDir = cfg.messagesDir;
|
|
28
|
+
} catch {/* ignore */}
|
|
29
|
+
} else {
|
|
30
|
+
warn("translate.config.json not found — using default messages/ dir. Run `autoglot init` first if this is a new project.");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const sourcePath = join(cwd, messagesDir, "en.json");
|
|
34
|
+
if (!existsSync(sourcePath)) {
|
|
35
|
+
err(`Source file ${messagesDir}/en.json not found. Run \`autoglot init\` first.`);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let added = 0;
|
|
40
|
+
let already = 0;
|
|
41
|
+
for (const code of positional) {
|
|
42
|
+
if (!/^[a-z]{2,3}(-[A-Z]{2})?$/.test(code)) {
|
|
43
|
+
warn(`"${code}" doesn't look like an ISO locale code. Skipping.`);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const localePath = join(cwd, messagesDir, `${code}.json`);
|
|
47
|
+
if (existsSync(localePath)) {
|
|
48
|
+
info(`${messagesDir}/${code}.json already exists — leaving it alone.`);
|
|
49
|
+
already++;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
writeFileSync(localePath, "{}\n");
|
|
53
|
+
ok(`${messagesDir}/${code}.json`);
|
|
54
|
+
added++;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
step("Next");
|
|
58
|
+
if (added > 0) {
|
|
59
|
+
info(`Push to a branch — autoglot will populate ${added} new file${added === 1 ? "" : "s"} on the next run.`);
|
|
60
|
+
} else if (already > 0) {
|
|
61
|
+
info("Nothing to do. All requested locales already exist.");
|
|
62
|
+
}
|
|
63
|
+
}
|
package/bin/cli.mjs
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// autoglot CLI dispatcher.
|
|
3
|
+
//
|
|
4
|
+
// Subcommands:
|
|
5
|
+
// autoglot → run translation (default; reads translate.config.json)
|
|
6
|
+
// autoglot init → interactive scaffold for a new project
|
|
7
|
+
// autoglot add <locale> → add a new target locale
|
|
8
|
+
// autoglot doctor → health check of the current setup
|
|
9
|
+
// autoglot --version | -v → print version
|
|
10
|
+
// autoglot --help | -h → print help
|
|
11
|
+
//
|
|
12
|
+
// Anything that doesn't match a subcommand falls through to the
|
|
13
|
+
// translation engine, so action.yml's `npx -y autoglot --source=... --check`
|
|
14
|
+
// continues to work without changes.
|
|
15
|
+
|
|
16
|
+
import { readFileSync } from "node:fs";
|
|
17
|
+
|
|
18
|
+
const SUBCOMMANDS = new Set(["init", "add", "doctor", "extract", "help"]);
|
|
19
|
+
const argv = process.argv.slice(2);
|
|
20
|
+
const first = argv[0];
|
|
21
|
+
|
|
22
|
+
const HELP = `autoglot — AI-powered i18n translation bot
|
|
23
|
+
|
|
24
|
+
Usage
|
|
25
|
+
npx autoglot Run translation (uses translate.config.json)
|
|
26
|
+
npx autoglot init Interactive setup for a new project
|
|
27
|
+
npx autoglot add <locale> Add an empty target locale file
|
|
28
|
+
npx autoglot doctor Health check of your autoglot setup
|
|
29
|
+
npx autoglot extract Scan source files for hardcoded strings
|
|
30
|
+
npx autoglot --version | -v Print version
|
|
31
|
+
npx autoglot --help | -h Print help
|
|
32
|
+
|
|
33
|
+
Translation flags (when no subcommand given)
|
|
34
|
+
--check CI gate: exit 1 if lock != source. No AI call.
|
|
35
|
+
--dry-run Show plan, no AI call, no writes.
|
|
36
|
+
--quiet Suppress per-locale progress (auto-disabled in CI).
|
|
37
|
+
--locales=de,fr Restrict run to specific locales.
|
|
38
|
+
--model=<id> Override the configured model (default: claude-haiku-4-5).
|
|
39
|
+
--source=<path> Override config.source (default: messages/en.json).
|
|
40
|
+
--messages-dir=<path> Override config.messagesDir (default: messages).
|
|
41
|
+
--lock-file=<path> Override config.lockFile (default: translate.lock).
|
|
42
|
+
--config=<path> Custom config file path (default: translate.config.json).
|
|
43
|
+
--import-languine[=<path>] Seed our lock file from a languine.lock and exit.
|
|
44
|
+
--summary-path=<path> Where to write the markdown summary.
|
|
45
|
+
|
|
46
|
+
Environment
|
|
47
|
+
ANTHROPIC_API_KEY Required for real runs. Not needed for --check or --dry-run.
|
|
48
|
+
|
|
49
|
+
Docs
|
|
50
|
+
https://github.com/ffcabbar/autoglot
|
|
51
|
+
`;
|
|
52
|
+
|
|
53
|
+
if (first === "--version" || first === "-v") {
|
|
54
|
+
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
55
|
+
process.stdout.write(`${pkg.version}\n`);
|
|
56
|
+
process.exit(0);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (first === "--help" || first === "-h" || first === "help") {
|
|
60
|
+
process.stdout.write(HELP);
|
|
61
|
+
process.exit(0);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (first === "init") {
|
|
65
|
+
const m = await import("./init.mjs");
|
|
66
|
+
await m.run(argv.slice(1));
|
|
67
|
+
process.exit(0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (first === "add") {
|
|
71
|
+
const m = await import("./add.mjs");
|
|
72
|
+
await m.run(argv.slice(1));
|
|
73
|
+
process.exit(0);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (first === "doctor") {
|
|
77
|
+
const m = await import("./doctor.mjs");
|
|
78
|
+
await m.run(argv.slice(1));
|
|
79
|
+
process.exit(0);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (first === "extract") {
|
|
83
|
+
const m = await import("./extract.mjs");
|
|
84
|
+
await m.run(argv.slice(1));
|
|
85
|
+
process.exit(0);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Unknown subcommand sanity check: if first arg looks like a subcommand
|
|
89
|
+
// (no leading dash, not a known one), warn the user instead of silently
|
|
90
|
+
// passing it through to the translator.
|
|
91
|
+
if (first && !first.startsWith("-") && !SUBCOMMANDS.has(first)) {
|
|
92
|
+
process.stderr.write(`autoglot: unknown subcommand '${first}'.\n`);
|
|
93
|
+
process.stderr.write(`Run \`autoglot --help\` for the list of subcommands.\n`);
|
|
94
|
+
process.exit(2);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Fall through to the translation engine.
|
|
98
|
+
await import("./translate.mjs");
|
package/bin/detect.mjs
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Detect the framework in the current working directory.
|
|
2
|
+
//
|
|
3
|
+
// Pure helper for ease of testing: takes a `pkg` (parsed package.json) and a
|
|
4
|
+
// list of paths that exist on disk, returns a framework descriptor.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {{
|
|
8
|
+
* key: "nextjs-app" | "nextjs-pages" | "react-native" | "vite-react" | "vue" | "generic",
|
|
9
|
+
* label: string,
|
|
10
|
+
* runtime: "next-intl" | "react-i18next" | "vue-i18n" | null,
|
|
11
|
+
* note?: string
|
|
12
|
+
* }} Framework
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {object} pkg parsed package.json (or {} if none)
|
|
17
|
+
* @param {Set<string>} present set of relative paths that exist (e.g. "src/app", "pages")
|
|
18
|
+
* @returns {Framework}
|
|
19
|
+
*/
|
|
20
|
+
export function detect(pkg, present) {
|
|
21
|
+
const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
|
|
22
|
+
|
|
23
|
+
if (deps["react-native"]) {
|
|
24
|
+
return {
|
|
25
|
+
key: "react-native",
|
|
26
|
+
label: "React Native",
|
|
27
|
+
runtime: "react-i18next",
|
|
28
|
+
note: "Will scaffold src/i18n/index.ts with react-i18next + AsyncStorage-aware locale init.",
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (deps["next"]) {
|
|
33
|
+
const hasApp = present.has("src/app") || present.has("app");
|
|
34
|
+
const hasPages = present.has("src/pages") || present.has("pages");
|
|
35
|
+
if (hasApp || (!hasApp && !hasPages)) {
|
|
36
|
+
return {
|
|
37
|
+
key: "nextjs-app",
|
|
38
|
+
label: "Next.js (App Router)",
|
|
39
|
+
runtime: "next-intl",
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
key: "nextjs-pages",
|
|
44
|
+
label: "Next.js (Pages Router)",
|
|
45
|
+
runtime: "next-i18next",
|
|
46
|
+
note: "We'll scaffold messages + workflow and print the next-i18next wiring steps. We don't auto-modify next.config.js or _app.tsx.",
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (deps["nuxt"] || deps["vue"]) {
|
|
51
|
+
return {
|
|
52
|
+
key: "vue",
|
|
53
|
+
label: "Vue / Nuxt",
|
|
54
|
+
runtime: "vue-i18n",
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (deps["vite"] && deps["react"]) {
|
|
59
|
+
return {
|
|
60
|
+
key: "vite-react",
|
|
61
|
+
label: "Vite + React",
|
|
62
|
+
runtime: "react-i18next",
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
key: "generic",
|
|
68
|
+
label: "Generic / no framework detected",
|
|
69
|
+
runtime: null,
|
|
70
|
+
note: "We'll scaffold messages + workflow only. Pair with any i18n library that reads JSON.",
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Built-in catalog of common locales for the multi-select.
|
|
76
|
+
* Display name + ISO code.
|
|
77
|
+
*/
|
|
78
|
+
export const LOCALE_CATALOG = [
|
|
79
|
+
{ code: "es", label: "Spanish (es)" },
|
|
80
|
+
{ code: "fr", label: "French (fr)" },
|
|
81
|
+
{ code: "de", label: "German (de)" },
|
|
82
|
+
{ code: "tr", label: "Turkish (tr)" },
|
|
83
|
+
{ code: "pt", label: "Portuguese (pt)" },
|
|
84
|
+
{ code: "it", label: "Italian (it)" },
|
|
85
|
+
{ code: "ja", label: "Japanese (ja)" },
|
|
86
|
+
{ code: "ko", label: "Korean (ko)" },
|
|
87
|
+
{ code: "zh", label: "Chinese (zh)" },
|
|
88
|
+
{ code: "ru", label: "Russian (ru)" },
|
|
89
|
+
{ code: "ar", label: "Arabic (ar)" },
|
|
90
|
+
{ code: "nl", label: "Dutch (nl)" },
|
|
91
|
+
{ code: "pl", label: "Polish (pl)" },
|
|
92
|
+
{ code: "sv", label: "Swedish (sv)" },
|
|
93
|
+
{ code: "id", label: "Indonesian (id)" },
|
|
94
|
+
];
|
package/bin/doctor.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// `autoglot doctor` — health check.
|
|
2
|
+
//
|
|
3
|
+
// Verifies the setup is correct so launching CI for the first time doesn't
|
|
4
|
+
// fail at 2am. Read-only — never writes or modifies anything.
|
|
5
|
+
|
|
6
|
+
import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { ok, warn, err, info, step, c } from "./prompts.mjs";
|
|
9
|
+
|
|
10
|
+
export async function run() {
|
|
11
|
+
const cwd = process.cwd();
|
|
12
|
+
step("autoglot doctor");
|
|
13
|
+
|
|
14
|
+
let warnings = 0;
|
|
15
|
+
let errors = 0;
|
|
16
|
+
|
|
17
|
+
function pass(msg) { ok(msg); }
|
|
18
|
+
function w(msg) { warn(msg); warnings++; }
|
|
19
|
+
function e(msg) { err(msg); errors++; }
|
|
20
|
+
|
|
21
|
+
// 1. translate.config.json
|
|
22
|
+
let cfg = null;
|
|
23
|
+
const cfgPath = join(cwd, "translate.config.json");
|
|
24
|
+
if (existsSync(cfgPath)) {
|
|
25
|
+
try {
|
|
26
|
+
cfg = JSON.parse(readFileSync(cfgPath, "utf8"));
|
|
27
|
+
pass("translate.config.json found and parses.");
|
|
28
|
+
} catch (err) {
|
|
29
|
+
e(`translate.config.json failed to parse: ${err.message}`);
|
|
30
|
+
}
|
|
31
|
+
} else {
|
|
32
|
+
w("translate.config.json not found — autoglot will use defaults. Consider \`autoglot init\`.");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// 2. Source file
|
|
36
|
+
const messagesDir = cfg?.messagesDir || "messages";
|
|
37
|
+
const sourcePath = cfg?.source || join(messagesDir, "en.json");
|
|
38
|
+
if (existsSync(join(cwd, sourcePath))) {
|
|
39
|
+
let sourceObj;
|
|
40
|
+
try {
|
|
41
|
+
sourceObj = JSON.parse(readFileSync(join(cwd, sourcePath), "utf8"));
|
|
42
|
+
const keys = countLeafKeys(sourceObj);
|
|
43
|
+
if (keys === 0) w(`${sourcePath} has no keys yet. Add your strings before running autoglot.`);
|
|
44
|
+
else pass(`${sourcePath} parses with ${keys} key${keys === 1 ? "" : "s"}.`);
|
|
45
|
+
} catch (err) {
|
|
46
|
+
e(`${sourcePath} failed to parse: ${err.message}`);
|
|
47
|
+
}
|
|
48
|
+
} else {
|
|
49
|
+
e(`Source file ${sourcePath} not found.`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 3. Target locales
|
|
53
|
+
const messagesFull = join(cwd, messagesDir);
|
|
54
|
+
if (existsSync(messagesFull) && statSync(messagesFull).isDirectory()) {
|
|
55
|
+
const sourceBase = sourcePath.replace(`${messagesDir}/`, "").replace(".json", "");
|
|
56
|
+
const targets = readdirSync(messagesFull)
|
|
57
|
+
.filter((f) => f.endsWith(".json") && f !== `${sourceBase}.json`);
|
|
58
|
+
if (targets.length === 0) {
|
|
59
|
+
w(`No target locale files in ${messagesDir}/. Add some with \`autoglot add <locale>\`.`);
|
|
60
|
+
} else {
|
|
61
|
+
pass(`${targets.length} target locale${targets.length === 1 ? "" : "s"}: ${targets.map((f) => f.replace(".json", "")).join(", ")}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 4. Workflow
|
|
66
|
+
const workflowPath = join(cwd, ".github/workflows/translate.yml");
|
|
67
|
+
if (existsSync(workflowPath)) {
|
|
68
|
+
const workflow = readFileSync(workflowPath, "utf8");
|
|
69
|
+
if (workflow.includes("ffcabbar/autoglot")) {
|
|
70
|
+
pass(".github/workflows/translate.yml uses ffcabbar/autoglot.");
|
|
71
|
+
} else {
|
|
72
|
+
w(".github/workflows/translate.yml exists but doesn't reference ffcabbar/autoglot.");
|
|
73
|
+
}
|
|
74
|
+
if (workflow.includes("ANTHROPIC_API_KEY")) {
|
|
75
|
+
pass("Workflow references ANTHROPIC_API_KEY secret.");
|
|
76
|
+
} else {
|
|
77
|
+
w("Workflow doesn't reference ANTHROPIC_API_KEY. autoglot will fail without it.");
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
w(".github/workflows/translate.yml not found. Run \`autoglot init\` to create one, or add the workflow manually.");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 5. lock file format (if exists)
|
|
84
|
+
const lockPath = join(cwd, cfg?.lockFile || "translate.lock");
|
|
85
|
+
if (existsSync(lockPath)) {
|
|
86
|
+
const txt = readFileSync(lockPath, "utf8");
|
|
87
|
+
if (/^version:\s*1\b/m.test(txt)) {
|
|
88
|
+
pass("translate.lock has version 1 header.");
|
|
89
|
+
} else {
|
|
90
|
+
w("translate.lock exists but doesn't look like an autoglot lock file.");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// 6. ANTHROPIC_API_KEY in env (only relevant for local runs)
|
|
95
|
+
if (process.env.ANTHROPIC_API_KEY) {
|
|
96
|
+
pass("ANTHROPIC_API_KEY set in current shell.");
|
|
97
|
+
} else {
|
|
98
|
+
info("ANTHROPIC_API_KEY not set in this shell — fine for CI; only needed for local runs.");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Summary
|
|
102
|
+
step("Summary");
|
|
103
|
+
if (errors > 0) {
|
|
104
|
+
err(`${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}.`);
|
|
105
|
+
process.exit(1);
|
|
106
|
+
} else if (warnings > 0) {
|
|
107
|
+
warn(`${warnings} warning${warnings === 1 ? "" : "s"}, no errors. autoglot will run but you might want to address these.`);
|
|
108
|
+
} else {
|
|
109
|
+
ok("All clear. autoglot is healthy.");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function countLeafKeys(obj) {
|
|
114
|
+
if (typeof obj !== "object" || obj === null) return 1;
|
|
115
|
+
if (Array.isArray(obj)) return 0;
|
|
116
|
+
let n = 0;
|
|
117
|
+
for (const k of Object.keys(obj)) n += countLeafKeys(obj[k]);
|
|
118
|
+
return n;
|
|
119
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Pure helpers for `autoglot extract`. No I/O. Easy to test.
|
|
2
|
+
|
|
3
|
+
import { readdirSync, statSync } from "node:fs";
|
|
4
|
+
import { join, extname } from "node:path";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Recursive walk that pushes matching files into `out`.
|
|
8
|
+
* @param {string} dir
|
|
9
|
+
* @param {Set<string>} exts allow-list of extensions (with leading dot)
|
|
10
|
+
* @param {Set<string>} skipDirs directory basenames to skip
|
|
11
|
+
* @param {string[]} out accumulator
|
|
12
|
+
*/
|
|
13
|
+
export function walk(dir, exts, skipDirs, out) {
|
|
14
|
+
let entries;
|
|
15
|
+
try {
|
|
16
|
+
entries = readdirSync(dir);
|
|
17
|
+
} catch {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
for (const name of entries) {
|
|
21
|
+
if (name.startsWith(".") && name !== ".") {
|
|
22
|
+
// .vscode etc. — skip dotdirs except `.` itself
|
|
23
|
+
if (name === ".gitkeep" || name === ".npmignore") continue;
|
|
24
|
+
}
|
|
25
|
+
if (skipDirs.has(name)) continue;
|
|
26
|
+
const full = join(dir, name);
|
|
27
|
+
let st;
|
|
28
|
+
try {
|
|
29
|
+
st = statSync(full);
|
|
30
|
+
} catch {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (st.isDirectory()) {
|
|
34
|
+
walk(full, exts, skipDirs, out);
|
|
35
|
+
} else if (exts.has(extname(name))) {
|
|
36
|
+
out.push(full);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Find candidate user-facing strings in a source file.
|
|
43
|
+
* Looks at:
|
|
44
|
+
* 1. JSX text content between tags (>...<), no expressions inside
|
|
45
|
+
* 2. Common string-valued props: placeholder, aria-label, title, alt, label
|
|
46
|
+
*
|
|
47
|
+
* Returns Array<{ text: string, line: number }>.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} code the full file contents
|
|
50
|
+
*/
|
|
51
|
+
export function extractCandidates(code) {
|
|
52
|
+
const out = [];
|
|
53
|
+
|
|
54
|
+
// 1. JSX text content. Greedy on contents, lazy on whitespace at edges.
|
|
55
|
+
// The negative `[^<{}]` rules out JS expressions ({var}) and nested tags.
|
|
56
|
+
const jsxText = />([^<>{}]{1,500})</g;
|
|
57
|
+
let m;
|
|
58
|
+
while ((m = jsxText.exec(code)) !== null) {
|
|
59
|
+
const raw = m[1];
|
|
60
|
+
const text = raw.replace(/\s+/g, " ").trim();
|
|
61
|
+
if (isLikelyUserFacing(text)) {
|
|
62
|
+
out.push({ text, line: lineFromOffset(code, m.index + 1) });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 2. Common string-valued props.
|
|
67
|
+
const propRe = /\b(placeholder|aria-label|title|alt|label)\s*=\s*"([^"]{1,500})"/g;
|
|
68
|
+
while ((m = propRe.exec(code)) !== null) {
|
|
69
|
+
const text = m[2].trim();
|
|
70
|
+
if (isLikelyUserFacing(text)) {
|
|
71
|
+
out.push({ text, line: lineFromOffset(code, m.index) });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return dedupe(out);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function dedupe(arr) {
|
|
79
|
+
const seen = new Set();
|
|
80
|
+
const out = [];
|
|
81
|
+
for (const item of arr) {
|
|
82
|
+
const key = `${item.line}::${item.text}`;
|
|
83
|
+
if (seen.has(key)) continue;
|
|
84
|
+
seen.add(key);
|
|
85
|
+
out.push(item);
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Compute 1-based line number from a byte offset. */
|
|
91
|
+
export function lineFromOffset(code, offset) {
|
|
92
|
+
let line = 1;
|
|
93
|
+
for (let i = 0; i < offset && i < code.length; i++) {
|
|
94
|
+
if (code[i] === "\n") line++;
|
|
95
|
+
}
|
|
96
|
+
return line;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Heuristic: is this string something a user actually sees?
|
|
101
|
+
* Conservative — better to miss a real one than flag 100 false positives.
|
|
102
|
+
*
|
|
103
|
+
* Keep:
|
|
104
|
+
* - Anything with a space ("Get started", "Click to continue")
|
|
105
|
+
* - Strings starting with a capital letter that look like a sentence/word
|
|
106
|
+
*
|
|
107
|
+
* Skip:
|
|
108
|
+
* - Empty / very short / pure punctuation
|
|
109
|
+
* - All-digit / pure numeric formatting
|
|
110
|
+
* - URLs, paths, file extensions
|
|
111
|
+
* - Identifier-like (lowercase with dashes/underscores, no spaces) — likely CSS classes / tokens
|
|
112
|
+
* - Pure symbol strings ("→", "©")
|
|
113
|
+
*/
|
|
114
|
+
export function isLikelyUserFacing(text) {
|
|
115
|
+
if (!text || text.length < 2) return false;
|
|
116
|
+
if (text.length > 300) return false; // probably template / inline doc
|
|
117
|
+
|
|
118
|
+
if (!/[a-zA-Z]/.test(text)) return false; // need at least one letter
|
|
119
|
+
if (/^[\d.,$%\s+-]+$/.test(text)) return false; // pure numbers / monetary
|
|
120
|
+
if (/^https?:\/\//i.test(text)) return false; // URLs
|
|
121
|
+
if (/^\//.test(text) || /^\.\.?\//.test(text)) return false; // paths
|
|
122
|
+
if (/^[a-zA-Z][\w-]*\.(json|tsx?|jsx?|css|svg|png|jpg|gif|md|yml|yaml)$/i.test(text)) return false; // filenames
|
|
123
|
+
|
|
124
|
+
// Has whitespace = almost certainly user-facing copy.
|
|
125
|
+
if (/\s/.test(text)) return true;
|
|
126
|
+
|
|
127
|
+
// Single word: must start with a letter (kicks out "©", "→", "©2026", etc.)
|
|
128
|
+
if (!/^[A-Za-z]/.test(text)) return false;
|
|
129
|
+
|
|
130
|
+
// Identifier-pattern (lowercase + dashes/underscores/digits, no caps,
|
|
131
|
+
// no whitespace) → likely a CSS class, token, or variable name.
|
|
132
|
+
if (/^[a-z][\w-]*$/.test(text)) return false;
|
|
133
|
+
|
|
134
|
+
// ALL_CAPS or SCREAMING_SNAKE_CASE → constants, not copy.
|
|
135
|
+
if (/^[A-Z_]+$/.test(text)) return false;
|
|
136
|
+
|
|
137
|
+
// Anything else starting with a letter (e.g. "Submit", "Welcome!", "Hi-five")
|
|
138
|
+
// is likely user-facing single-word copy.
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Suggest a dotted key path for a hardcoded string.
|
|
144
|
+
* namespace = file path with conventional prefixes stripped
|
|
145
|
+
* key = camelCase of the first 1–3 words of the string
|
|
146
|
+
*
|
|
147
|
+
* @param {string} text the user-facing string
|
|
148
|
+
* @param {string} relPath file path relative to project root, e.g. "src/app/dashboard/page.tsx"
|
|
149
|
+
*/
|
|
150
|
+
export function suggestKey(text, relPath) {
|
|
151
|
+
const ns = pathToNamespace(relPath);
|
|
152
|
+
const key = textToCamelKey(text);
|
|
153
|
+
return ns ? `${ns}.${key}` : key;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function pathToNamespace(relPath) {
|
|
157
|
+
// Strip extension
|
|
158
|
+
let p = relPath.replace(/\.(tsx?|jsx?|vue|svelte)$/, "");
|
|
159
|
+
// Strip conventional prefixes
|
|
160
|
+
p = p.replace(/^(?:src\/)?(?:app\/|components\/|pages\/|screens\/)?/, "");
|
|
161
|
+
// Bracketed Next.js segments: drop them (e.g. [locale])
|
|
162
|
+
p = p.replace(/\[[^\]]+\]\/?/g, "");
|
|
163
|
+
// Drop trailing or whole-path "page" / "index" / "layout".
|
|
164
|
+
// Matches "page", "/page", "foo/page" — leaves "foo".
|
|
165
|
+
p = p.replace(/(^|\/)(page|index|layout)$/, "");
|
|
166
|
+
// Slashes → dots
|
|
167
|
+
p = p.replace(/\/+/g, ".").replace(/^\.+|\.+$/g, "");
|
|
168
|
+
return p;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function textToCamelKey(text) {
|
|
172
|
+
const words = text
|
|
173
|
+
.toLowerCase()
|
|
174
|
+
.replace(/[^a-z0-9\s]/g, " ")
|
|
175
|
+
.split(/\s+/)
|
|
176
|
+
.filter(Boolean)
|
|
177
|
+
.slice(0, 3);
|
|
178
|
+
if (words.length === 0) return "key";
|
|
179
|
+
return words[0] + words.slice(1).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Set a value at a dotted path on an object. Mutates `obj`. */
|
|
183
|
+
export function setNested(obj, dottedPath, value) {
|
|
184
|
+
const parts = dottedPath.split(".");
|
|
185
|
+
let cur = obj;
|
|
186
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
187
|
+
const k = parts[i];
|
|
188
|
+
if (typeof cur[k] !== "object" || cur[k] === null || Array.isArray(cur[k])) {
|
|
189
|
+
cur[k] = {};
|
|
190
|
+
}
|
|
191
|
+
cur = cur[k];
|
|
192
|
+
}
|
|
193
|
+
cur[parts[parts.length - 1]] = value;
|
|
194
|
+
return obj;
|
|
195
|
+
}
|