autoglot 0.4.1 → 0.4.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 CHANGED
@@ -41,8 +41,8 @@ Review the generated files, install the suggested i18n library, and add `ANTHROP
41
41
  Autoglot 0.4.0 adds unattended setup. From your app directory, pass a comma-separated list of target locales.
42
42
 
43
43
  ```bash
44
- npx --yes autoglot@0.4.1 init --locales=de,pt-BR
45
- npx --yes autoglot@0.4.1 --dry-run
44
+ npx --yes autoglot@0.4.2 init --locales=de,pt-BR
45
+ npx --yes autoglot@0.4.2 --dry-run
46
46
  ```
47
47
 
48
48
  Setup creates the missing files and skips paths that already exist. The dry run lists the keys to translate for `de` and `pt-BR` without an API key. Add `--install` to opt into installing the runtime libraries. If that install fails, unattended setup exits with an error after printing the retry command.
@@ -87,7 +87,11 @@ npx autoglot --help # full flag list
87
87
 
88
88
  ### Monorepo
89
89
 
90
- 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.
90
+ Run `autoglot init` in each app directory within your Git checkout. For example, run `npx autoglot init --locales=de` from `apps/web`.
91
+
92
+ Init creates an app-specific `translate-<id>.yml` in the repository root’s `.github/workflows/` directory. The workflow passes the app’s config to the Action and watches the config, source catalog, and target locale JSON files. Init uses the catalog paths from an existing app config and creates missing requested locale files at the configured destination. Use relative paths inside the checkout for generated workflows. If an existing app config omits `source`, `messagesDir`, or `lockFile`, init uses app-local defaults for scaffolding and prints the missing entries. Add those entries and rerun init to generate the workflow. If init reports that it cannot generate a scoped workflow, set it up manually. Each app gets its own workflow, and init skips existing files. If you already have a workflow for this app, keep only the one you want to run. If an earlier init put a workflow in the app’s own `.github/workflows/` directory, review the new root workflow before removing the old copy.
93
+
94
+ 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/web/translate.config.json`. Paths inside the config are relative to the config file. See the [monorepo example](https://github.com/ffcabbar/autoglot/tree/main/examples/monorepo) for an offline dry run.
91
95
 
92
96
  ## Quickstart — GitHub Action (manual setup)
93
97
 
package/bin/init.mjs CHANGED
@@ -9,8 +9,10 @@
9
9
  //
10
10
  // Skips existing files.
11
11
 
12
- import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync } from "node:fs";
13
- import { join, dirname, resolve } from "node:path";
12
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, lstatSync, realpathSync } from "node:fs";
13
+ import { basename, join, dirname, relative, sep, isAbsolute } from "node:path";
14
+ import { createHash } from "node:crypto";
15
+ import { findRepoRoot, resolvePaths } from "./config.mjs";
14
16
  import { spawnSync } from "node:child_process";
15
17
  import { ask, select, multiselect, confirm, info, ok, warn, err, step, c, closePrompts } from "./prompts.mjs";
16
18
  import { detect, LOCALE_CATALOG } from "./detect.mjs";
@@ -61,17 +63,92 @@ export function parseInitArgs(argv) {
61
63
  return opts;
62
64
  }
63
65
 
66
+ const CONFIG_NAME = "translate.config.json";
67
+
68
+ function checkoutPath(root, full) {
69
+ const path = relative(root, full);
70
+ if (path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path)) return null;
71
+ const segments = path.split(sep);
72
+ if (segments.some((segment) => {
73
+ const name = segment.toLowerCase();
74
+ if (process.platform === "win32") {
75
+ // Win32 ignores trailing dots and spaces and can expose a DOS short name.
76
+ return /^(?:\.git|git~1)[. ]*$/.test(name);
77
+ }
78
+ return name === ".git";
79
+ })) return null;
80
+ return segments.join("/");
81
+ }
82
+
83
+ function workflowFor(root, appDir, catalogs) {
84
+ const workflowName = appDir
85
+ ? `translate-${createHash("sha256").update(appDir).digest("hex").slice(0, 12)}`
86
+ : "translate";
87
+ return {
88
+ baseDir: root,
89
+ path: `.github/workflows/${workflowName}.yml`,
90
+ content: common.workflow({ appDir, workflowName, ...catalogs }),
91
+ protectParents: Boolean(appDir),
92
+ };
93
+ }
94
+
95
+ function symlinkInPath(baseDir, path) {
96
+ let full = baseDir;
97
+ for (const segment of path.split("/")) {
98
+ full = join(full, segment);
99
+ const entry = lstatSync(full, { throwIfNoEntry: false });
100
+ if (!entry) return null;
101
+ if (entry.isSymbolicLink()) return full;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ function scaffoldExists(file, cwd) {
107
+ const baseDir = file.baseDir || cwd;
108
+ if (file.protectParents) {
109
+ const symlink = symlinkInPath(baseDir, dirname(file.path).split(sep).join("/"));
110
+ if (symlink) throw new Error(`refusing to follow symbolic link: ${symlink}`);
111
+ }
112
+ // Preserve the entry itself, including a symbolic link with a missing target.
113
+ return lstatSync(join(baseDir, file.path), { throwIfNoEntry: false }) !== undefined;
114
+ }
115
+
64
116
  export async function run(argv = []) {
65
117
  const opts = parseInitArgs(argv);
66
118
  const defaultLocale = "en";
67
119
  const nonInteractive = opts.locales !== null;
68
- if (nonInteractive && opts.locales.some((locale) => !LOCALE_CODE.test(locale) || locale === defaultLocale)) {
69
- process.stderr.write("autoglot init: expected target locale codes other than en, e.g. --locales=de,pt-BR.\n");
120
+ const cwd = process.cwd();
121
+ const root = findRepoRoot(cwd) || cwd;
122
+ const appDir = checkoutPath(root, cwd);
123
+ if (appDir === null) {
124
+ err("Run init from a working tree directory.");
125
+ process.exitCode = 1;
126
+ closePrompts();
127
+ return;
128
+ }
129
+ const configPath = join(cwd, CONFIG_NAME);
130
+ const defaultSource = join(cwd, "messages/en.json");
131
+ const defaultMessagesDir = join(cwd, "messages");
132
+ let resolved;
133
+ const existingConfig = existsSync(configPath);
134
+ let rawConfig = {};
135
+ try {
136
+ resolved = resolvePaths({ config: configPath }, cwd);
137
+ if (existingConfig) rawConfig = JSON.parse(readFileSync(configPath, "utf8"));
138
+ } catch (error) {
139
+ err(error.message);
140
+ process.exitCode = 1;
141
+ closePrompts();
142
+ return;
143
+ }
144
+ const { source, messagesDir, lockFile } = resolved;
145
+ const sourceLocale = basename(source, ".json");
146
+ if (nonInteractive && opts.locales.some((locale) => !LOCALE_CODE.test(locale) || locale === sourceLocale)) {
147
+ process.stderr.write(`autoglot init: expected target locale codes other than ${sourceLocale}, e.g. --locales=de,pt-BR.\n`);
70
148
  process.exitCode = 1;
71
149
  return;
72
150
  }
73
151
 
74
- const cwd = process.cwd();
75
152
  step("autoglot init");
76
153
  info(`cwd: ${c.dim}${cwd}${c.reset}`);
77
154
 
@@ -102,7 +179,10 @@ export async function run(argv = []) {
102
179
  step("Locales");
103
180
  let targetLocales = opts.locales;
104
181
  if (!nonInteractive) {
105
- const localeChoices = LOCALE_CATALOG.map((l) => ({
182
+ const localeCatalog = sourceLocale === defaultLocale
183
+ ? LOCALE_CATALOG
184
+ : [{ code: "en", label: "English (en)" }, ...LOCALE_CATALOG];
185
+ const localeChoices = localeCatalog.filter((l) => l.code !== sourceLocale).map((l) => ({
106
186
  label: l.label,
107
187
  value: l.code,
108
188
  default: ["es", "de", "tr"].includes(l.code),
@@ -125,7 +205,35 @@ export async function run(argv = []) {
125
205
  }
126
206
  }
127
207
 
128
- ok(`Source: ${defaultLocale} → Targets: ${targetLocales.join(", ")}`);
208
+ const customCatalogs = source !== defaultSource || messagesDir !== defaultMessagesDir;
209
+ const sourcePath = checkoutPath(root, source);
210
+ const targetDir = checkoutPath(root, messagesDir);
211
+ const appConfig = checkoutPath(root, configPath);
212
+ const catalogPaths = [sourcePath, targetDir];
213
+ const localCatalogs = !catalogPaths.includes(null) &&
214
+ ![rawConfig.source, rawConfig.messagesDir].some((path) => path && isAbsolute(path));
215
+ const symlinkedCatalogs = (customCatalogs || appDir) && localCatalogs &&
216
+ catalogPaths.some((path) => path && symlinkInPath(root, path));
217
+ const externalDefaultMessagesDir = appDir && !customCatalogs && existsSync(defaultMessagesDir) &&
218
+ checkoutPath(realpathSync(root), realpathSync(defaultMessagesDir)) === null;
219
+ const scaffoldCatalogs = localCatalogs && !(customCatalogs && symlinkedCatalogs) &&
220
+ !externalDefaultMessagesDir;
221
+ const lockPath = checkoutPath(root, lockFile);
222
+ const localLock = lockPath !== null && !(rawConfig.lockFile && isAbsolute(rawConfig.lockFile)) &&
223
+ !(lockPath && symlinkInPath(root, lockPath));
224
+
225
+ if (targetLocales.includes(sourceLocale)) {
226
+ warn(`Skipping ${sourceLocale} because it is the configured source locale.`);
227
+ targetLocales = targetLocales.filter((locale) => locale !== sourceLocale);
228
+ }
229
+ if (!targetLocales.length) {
230
+ err("Need at least one target locale different from the source.");
231
+ process.exitCode = 1;
232
+ closePrompts();
233
+ return;
234
+ }
235
+
236
+ ok(`Source: ${customCatalogs ? relative(cwd, source) : defaultLocale} → Targets: ${targetLocales.join(", ")}`);
129
237
 
130
238
  // Note: we deliberately do NOT run `npm install` here. Auto-install of a
131
239
  // runtime i18n library is fragile (peer-dep mismatches across React 18/19,
@@ -135,7 +243,7 @@ export async function run(argv = []) {
135
243
  // Use the template's full runtimePackages list (e.g. RN needs both i18next
136
244
  // AND react-i18next, not just one) instead of the single fw.runtime label.
137
245
  let runtimeInstallHint = null;
138
- if (fw.runtime) {
246
+ if (fw.runtime && !customCatalogs) {
139
247
  const templateForHint = TEMPLATES[fw.key];
140
248
  const pkgs = templateForHint?.runtimePackages || [fw.runtime];
141
249
  const installed = hasPkg
@@ -152,48 +260,66 @@ export async function run(argv = []) {
152
260
  step("Plan");
153
261
  const filesToWrite = [];
154
262
 
155
- // Common files
156
- filesToWrite.push({
157
- path: "messages/en.json",
158
- content: common.exampleEnJson(),
159
- skipIfExists: true,
160
- });
161
- for (const loc of targetLocales) {
162
- filesToWrite.push({
163
- path: `messages/${loc}.json`,
164
- content: common.emptyLocale(),
165
- skipIfExists: true,
166
- });
263
+ if (scaffoldCatalogs) {
264
+ filesToWrite.push({ baseDir: root, path: sourcePath, content: common.exampleEnJson() });
265
+ for (const loc of targetLocales) {
266
+ filesToWrite.push({
267
+ baseDir: root,
268
+ path: checkoutPath(root, join(messagesDir, `${loc}.json`)),
269
+ content: common.emptyLocale(),
270
+ });
271
+ }
272
+ } else {
273
+ warn("Configured catalog paths require manual setup. Add any missing locale files in the configured messages directory.");
167
274
  }
168
275
  filesToWrite.push({
169
- path: "translate.config.json",
170
- content: common.translateConfig({ source: "messages/en.json", messagesDir: "messages" }),
171
- skipIfExists: true,
172
- });
173
- filesToWrite.push({
174
- path: ".github/workflows/translate.yml",
175
- content: common.workflow({ messagesDir: "messages" }),
176
- skipIfExists: true,
276
+ path: CONFIG_NAME,
277
+ content: common.translateConfig(),
177
278
  });
178
279
 
179
- // Framework-specific files
280
+ const symlinkedWorkflowPaths = appDir && (symlinkedCatalogs || symlinkInPath(root, appConfig));
281
+ const workflowPathsSupported = scaffoldCatalogs && localLock && !symlinkedWorkflowPaths &&
282
+ ![...catalogPaths, appConfig].some((path) => path.includes("${{"));
283
+ const missingPaths = appDir && existingConfig && workflowPathsSupported
284
+ ? Object.entries({ source, messagesDir, lockFile })
285
+ .filter(([key]) => !rawConfig[key])
286
+ : [];
287
+ let workflow;
288
+ if (missingPaths.length) {
289
+ const fields = missingPaths.map(([key, value]) => `${JSON.stringify(key)}: ${JSON.stringify(checkoutPath(cwd, value))}`).join(", ");
290
+ warn(`Add the missing app-relative paths to ${CONFIG_NAME} and rerun init to generate the workflow: ${fields}`);
291
+ } else if (workflowPathsSupported) {
292
+ workflow = workflowFor(root, appDir, { sourcePath, targetDir, customCatalogs });
293
+ filesToWrite.push(workflow);
294
+ } else {
295
+ warn("Autoglot could not generate scoped checkout paths. Review the configured paths and configure the workflow manually.");
296
+ }
297
+
298
+ // Framework templates import the default catalog paths.
180
299
  let followupNotes = [];
181
300
  const tpl = TEMPLATES[fw.key];
182
- if (tpl) {
301
+ if (tpl && !customCatalogs) {
183
302
  const hasExistingApp = present.has("src/app") || present.has("app");
184
303
  const ctx = { defaultLocale, locales: [defaultLocale, ...targetLocales], hasExistingApp };
185
304
  for (const f of tpl.files(ctx)) {
186
- filesToWrite.push({ path: f.path, content: f.content, skipIfExists: true });
305
+ filesToWrite.push({ path: f.path, content: f.content });
187
306
  }
188
307
  followupNotes = tpl.followupNotes(ctx);
189
308
  }
190
309
 
191
310
  // Show plan
192
311
  for (const f of filesToWrite) {
193
- const full = join(cwd, f.path);
194
- const exists = existsSync(full);
195
- const status = exists ? `${c.yellow}EXISTS (will skip)${c.reset}` : `${c.green}CREATE${c.reset}`;
196
- process.stdout.write(` ${status} ${f.path}\n`);
312
+ const baseDir = f.baseDir || cwd;
313
+ try {
314
+ const exists = scaffoldExists(f, cwd);
315
+ const status = exists ? `${c.yellow}EXISTS (will skip)${c.reset}` : `${c.green}CREATE${c.reset}`;
316
+ process.stdout.write(` ${status} ${relative(cwd, join(baseDir, f.path))}\n`);
317
+ } catch (error) {
318
+ err(error.message);
319
+ process.exitCode = 1;
320
+ closePrompts();
321
+ return;
322
+ }
197
323
  }
198
324
 
199
325
  if (!nonInteractive && !(await confirm("\nProceed?", true))) {
@@ -207,8 +333,9 @@ export async function run(argv = []) {
207
333
  let written = 0;
208
334
  let skipped = 0;
209
335
  for (const f of filesToWrite) {
210
- const full = join(cwd, f.path);
211
- if (existsSync(full)) {
336
+ const baseDir = f.baseDir || cwd;
337
+ const full = join(baseDir, f.path);
338
+ if (scaffoldExists(f, cwd)) {
212
339
  skipped++;
213
340
  continue;
214
341
  }
@@ -220,7 +347,7 @@ export async function run(argv = []) {
220
347
  skipped++;
221
348
  continue;
222
349
  }
223
- ok(f.path);
350
+ ok(relative(cwd, full));
224
351
  written++;
225
352
  }
226
353
 
@@ -270,9 +397,13 @@ export async function run(argv = []) {
270
397
  }
271
398
  numbered.push(
272
399
  `Add ${c.bold}ANTHROPIC_API_KEY${c.reset} to your repo secrets:\n ${c.dim}gh secret set ANTHROPIC_API_KEY${c.reset}`,
273
- `Edit ${c.bold}messages/en.json${c.reset} with real strings.`,
274
- `Push to a branch — autoglot will translate and commit \`messages/<locale>.json\` files.`,
275
400
  );
401
+ if (scaffoldCatalogs) numbered.push(`Edit ${c.bold}${relative(cwd, source)}${c.reset} with real strings.`);
402
+ if (workflow) {
403
+ numbered.push(appDir
404
+ ? `Review ${relative(cwd, join(root, workflow.path))}, then push to a branch.`
405
+ : "Push to a branch — autoglot will translate and commit `messages/<locale>.json` files.");
406
+ }
276
407
  for (const note of followupNotes) numbered.push(note);
277
408
  numbered.forEach((note, i) => {
278
409
  process.stdout.write(` ${c.dim}${i + 1}.${c.reset} ${note}\n`);
@@ -3,20 +3,32 @@
3
3
 
4
4
  /**
5
5
  * Generate the GitHub Actions workflow.
6
- * @param {{ messagesDir?: string }} [opts]
7
6
  */
8
7
  export function workflow(opts = {}) {
9
- const messagesDir = opts.messagesDir || "messages";
10
- return `name: translate
8
+ const { messagesDir = "messages", appDir = "", workflowName = "translate",
9
+ customCatalogs = false, sourcePath = `${appDir}/${messagesDir}/en.json`, targetDir = `${appDir}/${messagesDir}` } = opts;
10
+ const config = appDir ? `${appDir}/translate.config.json` : "translate.config.json";
11
+ // Escape GitHub's glob operators in the literal part of each path filter.
12
+ const pattern = (path) => path.replace(/[\\*?+![\]]/g, "\\$&");
13
+ const targetPrefix = targetDir ? `${targetDir}/` : "";
14
+ const paths = appDir || customCatalogs
15
+ ? [
16
+ `${pattern(targetPrefix)}*.json`,
17
+ ...(sourcePath.startsWith(targetPrefix) && /^[^/]+\.json$/.test(sourcePath.slice(targetPrefix.length))
18
+ ? [] : [pattern(sourcePath)]),
19
+ pattern(config),
20
+ ].map((path) => JSON.stringify(path))
21
+ : [`${messagesDir}/en.json`, config];
22
+ const configInput = /^\s/.test(config) ? `./${config}` : config;
23
+ return `name: ${workflowName}
11
24
  on:
12
25
  push:
13
26
  branches: ["**"]
14
27
  paths:
15
- - ${messagesDir}/en.json
16
- - translate.config.json
28
+ ${paths.map((path) => ` - ${path}`).join("\n")}
17
29
 
18
30
  concurrency:
19
- group: translate-\${{ github.ref }}
31
+ group: ${workflowName}-\${{ github.ref }}
20
32
  cancel-in-progress: true
21
33
 
22
34
  jobs:
@@ -30,7 +42,7 @@ jobs:
30
42
  - uses: ffcabbar/autoglot@v1
31
43
  with:
32
44
  anthropic-api-key: \${{ secrets.ANTHROPIC_API_KEY }}
33
- `;
45
+ ${appDir ? ` config: ${JSON.stringify(configInput)}\n` : ""}`;
34
46
  }
35
47
 
36
48
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autoglot",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
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": {