autoglot 0.2.2 → 0.3.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/bin/cli.mjs CHANGED
@@ -30,6 +30,16 @@ Usage
30
30
  npx autoglot --version | -v Print version
31
31
  npx autoglot --help | -h Print help
32
32
 
33
+ init flags
34
+ --install Install runtime i18n library after scaffolding.
35
+ --no-install Skip the interactive install prompt.
36
+ --pm=npm|yarn|pnpm|bun Override the auto-detected package manager.
37
+
38
+ extract flags
39
+ --write Merge candidates into messages/en.json (existing
40
+ keys are never overwritten).
41
+ --source=<path> Override the target file (default: messages/en.json).
42
+
33
43
  Translation flags (when no subcommand given)
34
44
  --check CI gate: exit 1 if lock != source. No AI call.
35
45
  --dry-run Show plan, no AI call, no writes.
package/bin/detect.mjs CHANGED
@@ -5,9 +5,9 @@
5
5
 
6
6
  /**
7
7
  * @typedef {{
8
- * key: "nextjs-app" | "nextjs-pages" | "react-native" | "vite-react" | "vue" | "generic",
8
+ * key: "nextjs-app" | "nextjs-pages" | "expo" | "react-native" | "vite-react" | "vue" | "generic",
9
9
  * label: string,
10
- * runtime: "next-intl" | "react-i18next" | "vue-i18n" | null,
10
+ * runtime: "next-intl" | "next-i18next" | "react-i18next" | "vue-i18n" | null,
11
11
  * note?: string
12
12
  * }} Framework
13
13
  */
@@ -20,12 +20,24 @@
20
20
  export function detect(pkg, present) {
21
21
  const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
22
22
 
23
+ // Expo before react-native: an Expo app has BOTH `expo` and `react-native` as
24
+ // deps, but Expo has a cleaner device-locale API (expo-localization) so we
25
+ // give it the dedicated template.
26
+ if (deps["expo"]) {
27
+ return {
28
+ key: "expo",
29
+ label: "Expo",
30
+ runtime: "react-i18next",
31
+ note: "Will scaffold src/i18n/index.ts with react-i18next + expo-localization for device-locale auto-detect.",
32
+ };
33
+ }
34
+
23
35
  if (deps["react-native"]) {
24
36
  return {
25
37
  key: "react-native",
26
38
  label: "React Native",
27
39
  runtime: "react-i18next",
28
- note: "Will scaffold src/i18n/index.ts with react-i18next + AsyncStorage-aware locale init.",
40
+ note: "Will scaffold src/i18n/index.ts with react-i18next. Pair with react-native-localize for device locale.",
29
41
  };
30
42
  }
31
43
 
@@ -179,6 +179,46 @@ function textToCamelKey(text) {
179
179
  return words[0] + words.slice(1).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
180
180
  }
181
181
 
182
+ /**
183
+ * Look up a value at a dotted path. Returns `undefined` if the path
184
+ * doesn't fully exist or hits a non-object midway.
185
+ */
186
+ export function getNested(obj, dottedPath) {
187
+ const parts = dottedPath.split(".");
188
+ let cur = obj;
189
+ for (const k of parts) {
190
+ if (cur === null || typeof cur !== "object" || Array.isArray(cur)) return undefined;
191
+ cur = cur[k];
192
+ }
193
+ return cur;
194
+ }
195
+
196
+ /**
197
+ * Merge new candidate keys into an existing messages object.
198
+ * Returns { merged, added, skipped }:
199
+ * - merged: the new object (does not mutate the input)
200
+ * - added: [{key, text}] entries that were newly written
201
+ * - skipped: [{key, existing, text}] entries that already had a value
202
+ *
203
+ * Existing keys are NEVER overwritten — extract --write is meant to be
204
+ * safe to run repeatedly without clobbering hand-curated translations.
205
+ */
206
+ export function mergeKeys(existing, candidates) {
207
+ const merged = structuredClone(existing ?? {});
208
+ const added = [];
209
+ const skipped = [];
210
+ for (const cand of candidates) {
211
+ const current = getNested(merged, cand.key);
212
+ if (typeof current === "string") {
213
+ skipped.push({ key: cand.key, existing: current, text: cand.text });
214
+ continue;
215
+ }
216
+ setNested(merged, cand.key, cand.text);
217
+ added.push({ key: cand.key, text: cand.text });
218
+ }
219
+ return { merged, added, skipped };
220
+ }
221
+
182
222
  /** Set a value at a dotted path on an object. Mutates `obj`. */
183
223
  export function setNested(obj, dottedPath, value) {
184
224
  const parts = dottedPath.split(".");
package/bin/extract.mjs CHANGED
@@ -9,7 +9,7 @@
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, readdirSync, statSync, existsSync } from "node:fs";
12
+ import { readFileSync, writeFileSync, readdirSync, statSync, existsSync, mkdirSync } from "node:fs";
13
13
  import { join, relative, extname, dirname } from "node:path";
14
14
  import { step, info, ok, warn, err, c } from "./prompts.mjs";
15
15
  import {
@@ -18,6 +18,7 @@ import {
18
18
  isLikelyUserFacing,
19
19
  suggestKey,
20
20
  setNested,
21
+ mergeKeys,
21
22
  } from "./extract-helpers.mjs";
22
23
 
23
24
  export const SCAN_EXTS = new Set([".tsx", ".jsx", ".ts", ".js", ".vue", ".svelte"]);
@@ -27,7 +28,23 @@ export const SKIP_DIRS = new Set([
27
28
  "coverage", ".vercel", ".cache", ".parcel-cache", "out", "public",
28
29
  ]);
29
30
 
30
- export async function run(args) {
31
+ /**
32
+ * Parse `extract`-specific flags. Unknown flags are ignored (forward-compat).
33
+ *
34
+ * --write merge candidates into messages/en.json (skips existing keys)
35
+ * --source=<path> override the target file (default: messages/en.json)
36
+ */
37
+ export function parseExtractArgs(argv) {
38
+ const opts = { write: false, source: null };
39
+ for (const arg of argv) {
40
+ if (arg === "--write") opts.write = true;
41
+ else if (arg.startsWith("--source=")) opts.source = arg.slice("--source=".length);
42
+ }
43
+ return opts;
44
+ }
45
+
46
+ export async function run(args = []) {
47
+ const opts = parseExtractArgs(args);
31
48
  const cwd = process.cwd();
32
49
  step("autoglot extract");
33
50
 
@@ -88,13 +105,47 @@ export async function run(args) {
88
105
  setNested(merged, cand.key, cand.text);
89
106
  }
90
107
 
91
- step("Suggested additions to messages/en.json");
92
- process.stdout.write(JSON.stringify(merged, null, 2) + "\n");
108
+ if (!opts.write) {
109
+ step("Suggested additions to messages/en.json");
110
+ process.stdout.write(JSON.stringify(merged, null, 2) + "\n");
111
+ }
93
112
 
94
113
  step("Summary");
95
114
  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"}.`);
96
115
 
116
+ if (opts.write) {
117
+ const target = opts.source || "messages/en.json";
118
+ const full = join(cwd, target);
119
+ let existing = {};
120
+ if (existsSync(full)) {
121
+ try {
122
+ existing = JSON.parse(readFileSync(full, "utf8"));
123
+ } catch (e) {
124
+ err(`Couldn't parse ${target}: ${e.message}. Aborting --write.`);
125
+ return;
126
+ }
127
+ }
128
+ const { merged: out, added, skipped } = mergeKeys(existing, allCandidates);
129
+
130
+ step(opts.source ? `Writing ${target}` : "Writing messages/en.json");
131
+ mkdirSync(dirname(full), { recursive: true });
132
+ writeFileSync(full, JSON.stringify(out, null, 2) + "\n");
133
+ ok(`${target} now has ${added.length} new key${added.length === 1 ? "" : "s"}.`);
134
+ if (skipped.length > 0) {
135
+ info(`${skipped.length} key${skipped.length === 1 ? "" : "s"} already existed and were left untouched:`);
136
+ for (const s of skipped.slice(0, 5)) {
137
+ process.stdout.write(` ${c.dim}${s.key} (kept: ${JSON.stringify(s.existing)})${c.reset}\n`);
138
+ }
139
+ if (skipped.length > 5) {
140
+ process.stdout.write(` ${c.dim}…and ${skipped.length - 5} more${c.reset}\n`);
141
+ }
142
+ }
143
+ step("Next");
144
+ info(`Review the new keys in ${c.bold}${target}${c.reset}, then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
145
+ return;
146
+ }
147
+
97
148
  step("Next");
98
- info(`Review the candidates above. Copy the relevant ones into ${c.bold}messages/en.json${c.reset}, then replace the hardcoded string in your component with a ${c.bold}t("${c.dim}<key>${c.reset}${c.bold}")${c.reset} call.`);
99
- info("autoglot extract is read-only by design — it never modifies your source.");
149
+ info(`Review the candidates above. Copy the relevant ones into ${c.bold}messages/en.json${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.`);
150
+ info("Default mode is read-only. Use --write to merge into messages/en.json (existing keys are never overwritten).");
100
151
  }
package/bin/init.mjs CHANGED
@@ -11,24 +11,53 @@
11
11
 
12
12
  import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
13
13
  import { join, dirname, resolve } from "node:path";
14
+ import { spawnSync } from "node:child_process";
14
15
  import { ask, select, multiselect, confirm, info, ok, warn, err, step, c, closePrompts } from "./prompts.mjs";
15
16
  import { detect, LOCALE_CATALOG } from "./detect.mjs";
17
+ import { detectPackageManager, installCommand, PACKAGE_MANAGERS } from "./pm.mjs";
16
18
  import * as common from "./templates/common.mjs";
17
19
  import * as nextAppRouter from "./templates/nextjs-app-router.mjs";
18
20
  import * as nextPagesRouter from "./templates/nextjs-pages-router.mjs";
19
21
  import * as reactNative from "./templates/react-native.mjs";
22
+ import * as expo from "./templates/expo.mjs";
20
23
  import * as viteReact from "./templates/vite-react.mjs";
21
24
  import * as vueI18n from "./templates/vue-i18n.mjs";
22
25
 
23
26
  const TEMPLATES = {
24
27
  "nextjs-app": nextAppRouter,
25
28
  "nextjs-pages": nextPagesRouter,
29
+ "expo": expo,
26
30
  "react-native": reactNative,
27
31
  "vite-react": viteReact,
28
32
  "vue": vueI18n,
29
33
  };
30
34
 
31
- export async function run() {
35
+ /**
36
+ * Parse `init`-specific flags. Unknown flags are ignored (forward-compat).
37
+ *
38
+ * --install opt-in: run the package manager to install runtime deps
39
+ * --pm=npm|yarn|pnpm|bun override the auto-detected package manager
40
+ * --no-install force off (useful in CI if a default ever flips)
41
+ */
42
+ export function parseInitArgs(argv) {
43
+ const opts = { install: false, installExplicit: false, pm: null };
44
+ for (const arg of argv) {
45
+ if (arg === "--install") {
46
+ opts.install = true;
47
+ opts.installExplicit = true;
48
+ } else if (arg === "--no-install") {
49
+ opts.install = false;
50
+ opts.installExplicit = true;
51
+ } else if (arg.startsWith("--pm=")) {
52
+ const v = arg.slice("--pm=".length);
53
+ if (PACKAGE_MANAGERS.includes(v)) opts.pm = v;
54
+ }
55
+ }
56
+ return opts;
57
+ }
58
+
59
+ export async function run(argv = []) {
60
+ const opts = parseInitArgs(argv);
32
61
  const cwd = process.cwd();
33
62
  step("autoglot init");
34
63
  info(`cwd: ${c.dim}${cwd}${c.reset}`);
@@ -179,14 +208,48 @@ export async function run() {
179
208
  written++;
180
209
  }
181
210
 
182
- // Final report + next steps
211
+ // Final report
183
212
  step("Done");
184
213
  info(`Wrote ${written} file${written === 1 ? "" : "s"}, skipped ${skipped} existing file${skipped === 1 ? "" : "s"}.`);
185
214
 
215
+ // Optionally install runtime deps. Default is OFF — auto-install across
216
+ // monorepos / mixed React versions is fragile. Opt in with --install.
217
+ let installSucceeded = false;
218
+ let installFailed = false;
219
+ if (runtimeInstallHint) {
220
+ const pkgs = runtimeInstallHint.split(" ").filter(Boolean);
221
+ let shouldInstall = opts.install;
222
+ if (!opts.installExplicit) {
223
+ shouldInstall = await confirm(
224
+ `Install runtime packages now (${pkgs.join(", ")})?`,
225
+ false,
226
+ );
227
+ }
228
+ if (shouldInstall) {
229
+ const pm = opts.pm || detectPackageManager(cwd);
230
+ const [bin, ...args] = installCommand(pm, pkgs);
231
+ step(`Installing with ${pm}`);
232
+ info(`${c.dim}${bin} ${args.join(" ")}${c.reset}`);
233
+ const res = spawnSync(bin, args, { stdio: "inherit", cwd });
234
+ if (res.status === 0) {
235
+ ok(`Installed ${pkgs.join(", ")} via ${pm}.`);
236
+ installSucceeded = true;
237
+ } else {
238
+ warn(`${pm} install exited with code ${res.status ?? "?"}. You can re-run manually.`);
239
+ installFailed = true;
240
+ }
241
+ }
242
+ }
243
+
186
244
  step("Next steps");
187
245
  const numbered = [];
188
- if (runtimeInstallHint) {
189
- numbered.push(`Install the runtime i18n library:\n ${c.dim}npm install ${runtimeInstallHint}${c.reset}`);
246
+ if (runtimeInstallHint && !installSucceeded) {
247
+ const hintPm = opts.pm || detectPackageManager(cwd);
248
+ const [bin, ...args] = installCommand(hintPm, runtimeInstallHint.split(" ").filter(Boolean));
249
+ const label = installFailed
250
+ ? `Retry installing the runtime i18n library:`
251
+ : `Install the runtime i18n library:`;
252
+ numbered.push(`${label}\n ${c.dim}${bin} ${args.join(" ")}${c.reset}`);
190
253
  }
191
254
  numbered.push(
192
255
  `Add ${c.bold}ANTHROPIC_API_KEY${c.reset} to your repo secrets:\n ${c.dim}gh secret set ANTHROPIC_API_KEY${c.reset}`,
package/bin/pm.mjs ADDED
@@ -0,0 +1,57 @@
1
+ // Package manager detection + install command construction.
2
+ // Pure helpers (no I/O) plus one thin filesystem wrapper for the CLI.
3
+
4
+ import { existsSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ export const PACKAGE_MANAGERS = ["npm", "yarn", "pnpm", "bun"];
8
+
9
+ /**
10
+ * Decide which package manager a project uses from its lockfile presence.
11
+ * Precedence: bun > pnpm > yarn > npm (most distinctive first).
12
+ *
13
+ * Pure function — takes the set of lockfile names that exist, returns a name.
14
+ * Use `detectPackageManager(cwd)` for the filesystem wrapper.
15
+ *
16
+ * @param {Set<string>} lockfiles e.g. new Set(["pnpm-lock.yaml"])
17
+ * @returns {"npm" | "yarn" | "pnpm" | "bun"}
18
+ */
19
+ export function detectFromLockfiles(lockfiles) {
20
+ if (lockfiles.has("bun.lockb") || lockfiles.has("bun.lock")) return "bun";
21
+ if (lockfiles.has("pnpm-lock.yaml")) return "pnpm";
22
+ if (lockfiles.has("yarn.lock")) return "yarn";
23
+ // package-lock.json or nothing → npm (safe default; ships with Node).
24
+ return "npm";
25
+ }
26
+
27
+ /** Filesystem wrapper around detectFromLockfiles. */
28
+ export function detectPackageManager(cwd) {
29
+ const candidates = ["bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock", "package-lock.json"];
30
+ const present = new Set();
31
+ for (const f of candidates) {
32
+ if (existsSync(join(cwd, f))) present.add(f);
33
+ }
34
+ return detectFromLockfiles(present);
35
+ }
36
+
37
+ /**
38
+ * Build the install command tokens for a package manager.
39
+ * Returns [bin, ...args] suitable for spawn().
40
+ *
41
+ * @param {"npm" | "yarn" | "pnpm" | "bun"} pm
42
+ * @param {string[]} packages e.g. ["i18next", "react-i18next"]
43
+ * @returns {string[]}
44
+ */
45
+ export function installCommand(pm, packages) {
46
+ switch (pm) {
47
+ case "yarn":
48
+ return ["yarn", "add", ...packages];
49
+ case "pnpm":
50
+ return ["pnpm", "add", ...packages];
51
+ case "bun":
52
+ return ["bun", "add", ...packages];
53
+ case "npm":
54
+ default:
55
+ return ["npm", "install", ...packages];
56
+ }
57
+ }
@@ -0,0 +1,66 @@
1
+ // Expo + react-i18next scaffold.
2
+ //
3
+ // Expo apps have `react-native` in deps too, but Expo offers a cleaner
4
+ // device-locale API via `expo-localization` (no native linking required).
5
+ // We scaffold an i18n init that auto-picks the device locale and falls
6
+ // back to the configured default.
7
+
8
+ /** @param {{ defaultLocale: string, locales: string[] }} ctx */
9
+ export function indexTs(ctx) {
10
+ const imports = ctx.locales
11
+ .map((l) => `import ${jsId(l)} from "../../messages/${l}.json";`)
12
+ .join("\n");
13
+ const resources = ctx.locales
14
+ .map((l) => ` ${quoteIfNeeded(l)}: { translation: ${jsId(l)} },`)
15
+ .join("\n");
16
+ const localesArr = ctx.locales.map((l) => JSON.stringify(l)).join(", ");
17
+
18
+ return `import i18n from "i18next";
19
+ import { initReactI18next } from "react-i18next";
20
+ import { getLocales } from "expo-localization";
21
+
22
+ ${imports}
23
+
24
+ // Pick the first device locale that we have a translation for; otherwise
25
+ // fall back to the configured default.
26
+ const supported = new Set([${localesArr}]);
27
+ const deviceLocale = getLocales().find((l) => supported.has(l.languageTag) || supported.has(l.languageCode));
28
+ const initialLocale = deviceLocale?.languageTag ?? deviceLocale?.languageCode ?? "${ctx.defaultLocale}";
29
+
30
+ i18n.use(initReactI18next).init({
31
+ // i18next requires this on RN/Expo to avoid Intl polyfill differences.
32
+ compatibilityJSON: "v4",
33
+ resources: {
34
+ ${resources}
35
+ },
36
+ lng: supported.has(initialLocale) ? initialLocale : "${ctx.defaultLocale}",
37
+ fallbackLng: "${ctx.defaultLocale}",
38
+ interpolation: { escapeValue: false },
39
+ });
40
+
41
+ export default i18n;
42
+ `;
43
+ }
44
+
45
+ /** @param {{ defaultLocale: string, locales: string[] }} ctx */
46
+ export function files(ctx) {
47
+ return [{ path: "src/i18n/index.ts", content: indexTs(ctx) }];
48
+ }
49
+
50
+ export const runtimePackages = ["i18next", "react-i18next", "expo-localization"];
51
+
52
+ export function followupNotes() {
53
+ return [
54
+ "Import the i18n init early in App.tsx — before any t() calls:\n import \"./src/i18n\";",
55
+ "Use the useTranslation() hook in components: const { t } = useTranslation();",
56
+ "expo-localization is included — device locale is auto-detected on app start.",
57
+ "For Expo Router: place the import in app/_layout.tsx instead of App.tsx.",
58
+ ];
59
+ }
60
+
61
+ function jsId(loc) {
62
+ return loc.replace(/[^a-zA-Z0-9_$]/g, "_");
63
+ }
64
+ function quoteIfNeeded(loc) {
65
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(loc) ? loc : JSON.stringify(loc);
66
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autoglot",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
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"
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"
17
17
  },
18
18
  "keywords": [
19
19
  "i18n",