@tolkit/cli 0.0.0-stage → 0.2.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.
@@ -0,0 +1,78 @@
1
+ import { TolkitClient, readTolkitJson } from "../client.js";
2
+ import { isLocalePattern } from "../plan.js";
3
+ import { push } from "./push.js";
4
+ import { pull } from "./pull.js";
5
+ /** Pick the well-typed fields of a tolkit.json `sync` block. */
6
+ export function syncConfigFrom(file) {
7
+ const s = file.sync;
8
+ if (!s || typeof s !== "object" || Array.isArray(s))
9
+ return {};
10
+ const v = s;
11
+ const str = (x) => (typeof x === "string" && x.trim() ? x : undefined);
12
+ const out = {};
13
+ if (str(v.from))
14
+ out.from = str(v.from);
15
+ if (str(v.translations))
16
+ out.translations = str(v.translations);
17
+ if (Array.isArray(v.locales))
18
+ out.locales = v.locales.filter((x) => typeof x === "string");
19
+ else if (str(v.locales))
20
+ out.locales = str(v.locales);
21
+ if (typeof v.update === "boolean")
22
+ out.update = v.update;
23
+ if (typeof v.removeMissing === "boolean")
24
+ out.removeMissing = v.removeMissing;
25
+ if (str(v.plurals))
26
+ out.plurals = str(v.plurals);
27
+ if (str(v.format))
28
+ out.format = str(v.format);
29
+ if (str(v.out))
30
+ out.out = str(v.out);
31
+ return out;
32
+ }
33
+ /** Merge flags over the sync block into push options and pull options. */
34
+ export function resolveSync(cfg, flags) {
35
+ const translations = flags.translations ?? cfg.translations;
36
+ const locales = flags.locales ?? (Array.isArray(cfg.locales) ? cfg.locales.join(",") : cfg.locales);
37
+ const pushOpts = {
38
+ from: flags.from ?? cfg.from,
39
+ translations,
40
+ locales,
41
+ update: flags.update ?? cfg.update,
42
+ "remove-missing": flags["remove-missing"] ?? cfg.removeMissing,
43
+ plurals: flags.plurals ?? cfg.plurals,
44
+ yes: flags.yes,
45
+ "dry-run": flags["dry-run"],
46
+ scan: flags.scan,
47
+ root: flags.root,
48
+ };
49
+ const out = flags.out ?? cfg.out ?? (translations && isLocalePattern(translations) ? translations : ".");
50
+ return { push: pushOpts, pull: { format: flags.format ?? cfg.format, out, source: pushOpts.from } };
51
+ }
52
+ /** `tolkit sync`: push (per the tolkit.json `sync` block + flags), then pull every locale. */
53
+ export async function sync(cfg, flags) {
54
+ const plan = resolveSync(syncConfigFrom(await readTolkitJson()), flags);
55
+ if (!plan.push.from && !plan.push.translations) {
56
+ throw new Error('sync needs a source file: pass --from / --translations or add { "sync": { "from": "locales/en.json" } } to tolkit.json');
57
+ }
58
+ const client = new TolkitClient(cfg);
59
+ // Without --update the pull would replace local edits that differ from the
60
+ // server, so refuse up front unless the user opted to discard them.
61
+ const res = await push(cfg, { ...plan.push, refuseConflicts: !flags.force }, client);
62
+ if (res.aborted) {
63
+ console.log("sync: push aborted, not pulling");
64
+ return;
65
+ }
66
+ if (flags["dry-run"]) {
67
+ if (res.conflicts && !plan.push.update && !flags.force) {
68
+ console.log(`sync --dry-run: ${res.conflicts} local value(s) differ from the server; sync would stop (pass --update or --force)`);
69
+ return;
70
+ }
71
+ console.log(`sync --dry-run: would then pull every locale to ${plan.pull.out} (${plan.pull.format ?? "json"})`);
72
+ return;
73
+ }
74
+ if (res.conflicts && !plan.push.update) {
75
+ console.warn(`sync --force: discarding ${res.conflicts} local value(s) that differ from the server`);
76
+ }
77
+ await pull(cfg, plan.pull, client);
78
+ }
@@ -0,0 +1,16 @@
1
+ /** Nested/flat JSON object → flat `{ "dot.key": "value" }`. Null/undefined leaves are dropped; other primitives are stringified. */
2
+ export function flatten(input, prefix = "") {
3
+ const out = {};
4
+ for (const [key, value] of Object.entries(input)) {
5
+ const path = prefix ? `${prefix}.${key}` : key;
6
+ if (value === null || value === undefined)
7
+ continue;
8
+ if (typeof value === "object" && !Array.isArray(value)) {
9
+ Object.assign(out, flatten(value, path));
10
+ }
11
+ else {
12
+ out[path] = String(value);
13
+ }
14
+ }
15
+ return out;
16
+ }
package/dist/glob.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A tiny glob matcher for `tolkit.json` `scan.include` / `scan.exclude` — no
3
+ * dependency, and no reliance on `path.matchesGlob` (experimental before Node
4
+ * 22.14). Paths are relative to the scan root with forward slashes.
5
+ *
6
+ * Supported: `**` (any depth, incl. none), `*` (within a segment), `?`,
7
+ * `{a,b}` alternation. A pattern without a `/` matches at any depth, like
8
+ * .gitignore (`*.test.ts`, `vendor`).
9
+ */
10
+ export function globToRegExp(glob) {
11
+ let g = glob.trim().replace(/\\/g, "/").replace(/^\.\//, "");
12
+ if (g.endsWith("/"))
13
+ g = g.slice(0, -1);
14
+ if (!g.includes("/"))
15
+ g = `**/${g}`;
16
+ return new RegExp(`^${translate(g)}$`);
17
+ }
18
+ function translate(g) {
19
+ let re = "";
20
+ for (let i = 0; i < g.length; i++) {
21
+ const c = g[i];
22
+ if (c === "*") {
23
+ if (g[i + 1] === "*") {
24
+ // `**/` → zero or more whole segments; a trailing `**` → anything
25
+ if (g[i + 2] === "/") {
26
+ re += "(?:.*/)?";
27
+ i += 2;
28
+ }
29
+ else {
30
+ re += ".*";
31
+ i += 1;
32
+ }
33
+ }
34
+ else
35
+ re += "[^/]*";
36
+ }
37
+ else if (c === "?") {
38
+ re += "[^/]";
39
+ }
40
+ else if (c === "{") {
41
+ const close = g.indexOf("}", i);
42
+ if (close === -1) {
43
+ re += "\\{";
44
+ continue;
45
+ }
46
+ const alts = g.slice(i + 1, close).split(",").map(translate);
47
+ re += `(?:${alts.join("|")})`;
48
+ i = close;
49
+ }
50
+ else {
51
+ re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
52
+ }
53
+ }
54
+ return re;
55
+ }
56
+ /** A compiled pattern set; `test` is true if any pattern matches. */
57
+ export function globSet(patterns) {
58
+ const res = patterns.filter((p) => p.trim()).map(globToRegExp);
59
+ return { test: (path) => res.some((r) => r.test(path)) };
60
+ }
61
+ /**
62
+ * True if `path` or any of its ancestor directories matches — so excluding
63
+ * `vendor` or `src/generated` excludes everything beneath them.
64
+ */
65
+ export function matchesSelfOrAncestor(set, path) {
66
+ const parts = path.split("/");
67
+ for (let i = 1; i <= parts.length; i++) {
68
+ if (set.test(parts.slice(0, i).join("/")))
69
+ return true;
70
+ }
71
+ return false;
72
+ }
package/dist/index.js ADDED
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { resolveConfig } from "./client.js";
4
+ import { pull } from "./commands/pull.js";
5
+ import { push } from "./commands/push.js";
6
+ import { check, normalizeArgv } from "./commands/check.js";
7
+ import { scan } from "./commands/scan.js";
8
+ import { sync } from "./commands/sync.js";
9
+ import { runMcp } from "./mcp.js";
10
+ const USAGE = `tolkit — translation CLI
11
+
12
+ Usage:
13
+ tolkit pull [--locale <code> | --locales a,b] [--source <file.json>] [--format <id>] [--out <dir | "locales/{locale}.json">]
14
+ tolkit push [--from <file.json>] [--translations <pattern>] [--locales a,b] [--update]
15
+ [--remove-missing [--yes]] [--fail-on-conflict] [--dry-run] [--scan] [--root <dir>] [--plurals i18next]
16
+ tolkit sync [push flags] [--force] [--format <id>] [--out <dir | pattern>]
17
+ tolkit scan [--root <dir>] [--dry-run]
18
+ tolkit check [--from <file.json>] [--complete] [--reviewed[=<pct>]] [--qa[=errors|warnings]]
19
+ tolkit mcp
20
+
21
+ pull downloads target locales (skips the source locale by default); --source patches Tolkit-only source edits in-place.
22
+
23
+ push --update overwrites differing source values (default: only empty ones are filled).
24
+ push --translations "locales/{locale}.json" pushes target locales (fills empty cells; --update overwrites).
25
+ push --remove-missing deletes server keys absent from --from (asks on a TTY; --yes in CI).
26
+ push --dry-run prints the create/update/delete plan and writes nothing.
27
+ sync = push (tolkit.json "sync": { from, translations, locales, update, removeMissing, plurals, format, out }) then pull every locale.
28
+ sync stops if local values differ from the server: --update pushes them, --force discards them.
29
+ push reads descriptions, maxLength and plural from <file>.meta.json beside the source file, if present.
30
+ push --plurals i18next sends key_one/key_other siblings as one ICU plural key.
31
+ pull --format i18next writes plural keys as i18next key_one/key_other suffixes.
32
+ scan finds where each key is used in source (tolkit.json "scan": { include, exclude }).
33
+ check --reviewed fails if any locale is under 100% reviewed (or --reviewed=90 for 90%).
34
+ check --qa fails on QA errors (placeholders, max length, ICU syntax, plural forms); --qa=warnings on warnings too.
35
+
36
+ Auth: TOLKIT_API_KEY (or --key), TOLKIT_URL (or --url), or a tolkit.json { "url", "apiKey" }.
37
+ `;
38
+ async function main() {
39
+ const { values, positionals } = parseArgs({
40
+ args: normalizeArgv(process.argv.slice(2)),
41
+ allowPositionals: true,
42
+ options: {
43
+ locale: { type: "string" }, format: { type: "string" }, out: { type: "string" }, source: { type: "string" },
44
+ from: { type: "string" }, complete: { type: "boolean" }, reviewed: { type: "string" }, qa: { type: "string" },
45
+ scan: { type: "boolean" }, root: { type: "string" }, "dry-run": { type: "boolean" }, plurals: { type: "string" },
46
+ update: { type: "boolean" }, translations: { type: "string" }, locales: { type: "string" },
47
+ "remove-missing": { type: "boolean" }, "fail-on-conflict": { type: "boolean" }, force: { type: "boolean" }, yes: { type: "boolean", short: "y" },
48
+ url: { type: "string" }, key: { type: "string" }, help: { type: "boolean", short: "h" },
49
+ },
50
+ });
51
+ const cmd = positionals[0];
52
+ if (!cmd || values.help) {
53
+ console.log(USAGE);
54
+ return;
55
+ }
56
+ const cfg = await resolveConfig({ url: values.url, key: values.key });
57
+ switch (cmd) {
58
+ case "pull":
59
+ await pull(cfg, values);
60
+ break;
61
+ case "push": {
62
+ const outcome = await push(cfg, values);
63
+ if (values["fail-on-conflict"] && outcome.conflicts > 0)
64
+ process.exitCode = 1;
65
+ break;
66
+ }
67
+ case "sync":
68
+ await sync(cfg, values);
69
+ break;
70
+ case "scan":
71
+ await scan(cfg, values);
72
+ break;
73
+ case "check":
74
+ process.exitCode = await check(cfg, values);
75
+ break;
76
+ case "mcp":
77
+ await runMcp(cfg);
78
+ break;
79
+ default:
80
+ console.error(`Unknown command: ${cmd}\n\n${USAGE}`);
81
+ process.exitCode = 2;
82
+ }
83
+ }
84
+ main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exitCode = 1; });
package/dist/mcp.js ADDED
@@ -0,0 +1,22 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+ import { TolkitClient } from "./client.js";
5
+ export async function runMcp(cfg) {
6
+ const client = new TolkitClient(cfg);
7
+ const me = await client.me();
8
+ const server = new McpServer({ name: "tolkit-cli", version: "0.1.0" });
9
+ const text = (v) => ({ content: [{ type: "text", text: JSON.stringify(v, null, 2) }] });
10
+ server.registerTool("search_keys", { title: "search_keys", description: "Search this project's translation keys by name (case-insensitive). Project is fixed by the API key.", inputSchema: { query: z.string().default(""), limit: z.number().int().positive().max(500).optional() } }, async ({ query, limit }) => text(await client.search(me.projectId, query, limit ?? 500)));
11
+ server.registerTool("list_locales", { title: "list_locales", description: "List this project's locales (code, name, direction).", inputSchema: {} }, async () => text({ locales: me.locales }));
12
+ server.registerTool("coverage", { title: "coverage", description: "Per-locale translation completeness (% of keys filled).", inputSchema: {} }, async () => text(await client.coverage(me.projectId)));
13
+ server.registerTool("qa_issues", { title: "qa_issues", description: "Run translation QA checks and list problems ({ key, locale, code, severity, message }) with counts. Errors: missing/extra placeholders, over max length. Warnings: punctuation, whitespace, identical to source, brackets, glossary / do-not-translate terms. Optional locale and severity filters.", inputSchema: { locale: z.string().min(1).optional(), severity: z.enum(["error", "warning"]).optional() } }, async ({ locale, severity }) => text(await client.qa(me.projectId, { locale, severity })));
14
+ server.registerTool("get_translations", { title: "get_translations", description: "Download a locale's translations in a chosen format (json, yaml, po, ...). Defaults to json.", inputSchema: { locale: z.string().min(1), format: z.string().optional() } }, async ({ locale, format }) => ({ content: [{ type: "text", text: await client.download(me.projectId, locale, format ?? "json") }] }));
15
+ if (me.scope === "readwrite") {
16
+ server.registerTool("add_keys", { title: "add_keys", description: "Add translation keys + source text (and an optional translator-facing description and maxLength in characters) to this project. Existing keys are skipped, but a non-empty description or a maxLength updates theirs. Requires a read-write key.", inputSchema: { keys: z.array(z.object({ key: z.string().min(1), source: z.string().optional(), description: z.string().max(2000).optional(), maxLength: z.number().int().positive().optional() })).min(1).max(1000) } }, async ({ keys }) => text(await client.addKeys(me.projectId, keys)));
17
+ server.registerTool("set_translations", { title: "set_translations", description: "Write translation values for one locale by key name (ICU MessageFormat; an empty string clears). Returns { updated, unchanged, created, unknownKeys, blocked }. state \"reviewed\" also marks them reviewed, except keys with QA errors (listed in blocked) unless force. Requires a read-write key.", inputSchema: { locale: z.string().min(1), values: z.record(z.string().min(1), z.string()), state: z.enum(["translated", "reviewed"]).optional(), createMissingKeys: z.boolean().optional(), force: z.boolean().optional() } }, async (args) => text(await client.putTranslations(me.projectId, args)));
18
+ server.registerTool("update_key", { title: "update_key", description: "Update one key by name: rename (newName, must be unique), set/clear description and maxLength, toggle plural forms (isPlural, pluralArg). Requires a read-write key.", inputSchema: { name: z.string().min(1), newName: z.string().min(1).optional(), description: z.string().max(2000).nullable().optional(), maxLength: z.number().int().positive().nullable().optional(), isPlural: z.boolean().optional(), pluralArg: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/).optional() } }, async ({ name, newName, ...rest }) => text(await client.patchKey(me.projectId, name, { ...rest, ...(newName !== undefined ? { name: newName } : {}) })));
19
+ server.registerTool("delete_keys", { title: "delete_keys", description: "Delete keys by name with all their translations (irreversible). Returns { deleted, unknown }. Shared-library keys are never deleted. Requires a read-write key.", inputSchema: { names: z.array(z.string().min(1)).min(1).max(5000) } }, async ({ names }) => text(await client.deleteKeys(me.projectId, names)));
20
+ }
21
+ await server.connect(new StdioServerTransport());
22
+ }
package/dist/meta.js ADDED
@@ -0,0 +1,65 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename, dirname, extname, join } from "node:path";
3
+ /**
4
+ * Sidecar metadata for a source file: `en.json` → `en.meta.json` beside it.
5
+ *
6
+ * { "billing.seats": { "description": "Number of seats on the current plan.", "maxLength": 24, "role": "label" },
7
+ * "inbox.files": { "plural": true, "pluralArg": "count" } }
8
+ *
9
+ * `role` is what the string is on screen: action, label, status, heading,
10
+ * message or help. It decides grammar ("Open" on a button is a verb, on a
11
+ * status badge an adjective), and a role set here is never replaced by a scan.
12
+ *
13
+ * Keys are the same flat dot-keys `push` sends. A missing file, a missing key
14
+ * or a missing `description` / `maxLength` / `plural` / `role` are all fine; unknown properties
15
+ * are ignored so the format can grow without breaking older CLIs.
16
+ */
17
+ export function metaPathFor(sourceFile) {
18
+ const ext = extname(sourceFile);
19
+ return join(dirname(sourceFile), `${basename(sourceFile, ext)}.meta.json`);
20
+ }
21
+ export const KEY_ROLES = ["action", "label", "status", "heading", "message", "help"];
22
+ /** Parse sidecar JSON into key → meta, keeping only well-formed fields. */
23
+ export function parseMeta(raw) {
24
+ const out = {};
25
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
26
+ return out;
27
+ for (const [key, v] of Object.entries(raw)) {
28
+ if (!v || typeof v !== "object")
29
+ continue;
30
+ const { description: d, maxLength: n, plural: p, pluralArg: a, role: r } = v;
31
+ const meta = {};
32
+ if (typeof d === "string" && d.trim())
33
+ meta.description = d.trim();
34
+ // characters; the server's QA flags longer values (positive integers only)
35
+ if (typeof n === "number" && Number.isInteger(n) && n > 0)
36
+ meta.maxLength = n;
37
+ // plural key (values are ICU plurals); pluralArg names its argument
38
+ if (typeof p === "boolean")
39
+ meta.plural = p;
40
+ if (typeof a === "string" && /^[A-Za-z_][A-Za-z0-9_]*$/.test(a))
41
+ meta.pluralArg = a;
42
+ if (typeof r === "string" && KEY_ROLES.includes(r))
43
+ meta.role = r;
44
+ if (Object.keys(meta).length)
45
+ out[key] = meta;
46
+ }
47
+ return out;
48
+ }
49
+ /** Load the sidecar for `sourceFile`, or null if there isn't one. */
50
+ export async function loadMeta(sourceFile) {
51
+ const path = metaPathFor(sourceFile);
52
+ let text;
53
+ try {
54
+ text = await readFile(path, "utf8");
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ try {
60
+ return { path, meta: parseMeta(JSON.parse(text)) };
61
+ }
62
+ catch (e) {
63
+ throw new Error(`Could not parse ${path}: ${e instanceof Error ? e.message : e}`);
64
+ }
65
+ }
package/dist/plan.js ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Pure planning for `tolkit push` / `tolkit sync`: what to create, update and
3
+ * delete, decided from the local files and the server's current state. No I/O,
4
+ * so `--dry-run` prints exactly what a real run would do.
5
+ */
6
+ /**
7
+ * Three-way: `synced` is the source text the last push sent. When the server
8
+ * has it, a difference is attributed to whichever side changed since; without
9
+ * it (older servers, keys never pushed) local and server are compared directly.
10
+ */
11
+ export function planPush(local, server, opts = {}) {
12
+ const serverByName = new Map(server.map((k) => [k.name, k]));
13
+ const plan = { create: [], update: [], conflicts: [], edited: [], ack: [], remove: [], unchanged: 0 };
14
+ for (const [name, value] of Object.entries(local)) {
15
+ const key = serverByName.get(name);
16
+ if (!key) {
17
+ plan.create.push(name);
18
+ continue;
19
+ }
20
+ const current = key.source ?? "";
21
+ const synced = key.synced;
22
+ if (current === value || !value.trim()) {
23
+ plan.unchanged++;
24
+ if (value.trim() && synced !== value)
25
+ plan.ack.push(name);
26
+ }
27
+ else if (synced !== undefined && value === synced) {
28
+ plan.edited.push(name);
29
+ }
30
+ else if (!current.trim() || opts.update || (synced !== undefined && current === synced)) {
31
+ plan.update.push(name);
32
+ }
33
+ else {
34
+ plan.conflicts.push(name);
35
+ }
36
+ }
37
+ if (opts.removeMissing) {
38
+ for (const k of server)
39
+ if (!(k.name in local))
40
+ plan.remove.push(k.name);
41
+ }
42
+ return plan;
43
+ }
44
+ /**
45
+ * Target-locale values to push. Empty local values are skipped (a missing
46
+ * translation never clears the server's). Without `update` only empty server
47
+ * cells are filled.
48
+ */
49
+ export function planTranslations(local, serverValues, opts) {
50
+ const plan = { values: {}, filled: [], overwritten: [], unchanged: 0, skippedConflicts: [], unknown: [] };
51
+ for (const [name, value] of Object.entries(local)) {
52
+ if (!value.trim())
53
+ continue;
54
+ if (!opts.serverKeys.has(name)) {
55
+ plan.unknown.push(name);
56
+ continue;
57
+ }
58
+ const current = serverValues[name] ?? "";
59
+ if (current === value)
60
+ plan.unchanged++;
61
+ else if (!current.trim()) {
62
+ plan.filled.push(name);
63
+ plan.values[name] = value;
64
+ }
65
+ else if (opts.update) {
66
+ plan.overwritten.push(name);
67
+ plan.values[name] = value;
68
+ }
69
+ else
70
+ plan.skippedConflicts.push(name);
71
+ }
72
+ return plan;
73
+ }
74
+ /**
75
+ * Locale files for `--translations <pattern>`:
76
+ * - `locales/{locale}.json` — `{locale}` is replaced by each code;
77
+ * - `locales/*.json` — the first `*` is the locale;
78
+ * - `locales` (no placeholder) — a directory of `<locale>.json` files.
79
+ */
80
+ export function localePattern(pattern) {
81
+ const p = pattern.replace(/\\/g, "/");
82
+ if (p.includes("{locale}"))
83
+ return p;
84
+ if (p.includes("*"))
85
+ return p.replace("*", "{locale}");
86
+ return `${p.replace(/\/+$/, "")}/{locale}.json`;
87
+ }
88
+ export function resolveLocaleFiles(pattern, locales) {
89
+ const p = localePattern(pattern);
90
+ return locales.map((locale) => ({ locale, path: p.split("{locale}").join(locale) }));
91
+ }
92
+ /** True when `pattern` names files per locale (has `{locale}` or `*`). */
93
+ export const isLocalePattern = (pattern) => /\{locale\}|\*/.test(pattern);
94
+ const SAMPLE = 10;
95
+ /** "label: N" plus up to 10 names, for --dry-run output. */
96
+ export function formatList(label, names) {
97
+ if (names.length === 0)
98
+ return ` ${label}: 0`;
99
+ const shown = names.slice(0, SAMPLE).join(", ");
100
+ const more = names.length > SAMPLE ? `, … (+${names.length - SAMPLE} more)` : "";
101
+ return ` ${label}: ${names.length} — ${shown}${more}`;
102
+ }
103
+ export function formatPushPlan(plan, opts = {}) {
104
+ return [
105
+ formatList("create", plan.create),
106
+ formatList("update source", plan.update),
107
+ ...(plan.conflicts.length ? [formatList("changed on both sides (use --update to overwrite)", plan.conflicts)] : []),
108
+ ...(plan.edited.length ? [formatList("edited in Tolkit (kept; pull to bring it in)", plan.edited)] : []),
109
+ formatList("delete", plan.remove),
110
+ ` unchanged: ${plan.unchanged}`,
111
+ ].join("\n");
112
+ }
113
+ /** Readable side-by-side summary of conflicting source edits (repo vs Tolkit). */
114
+ export function formatSourceConflicts(names, local, server) {
115
+ if (names.length === 0)
116
+ return "";
117
+ const clip = (s) => (s.length > 72 ? `${s.slice(0, 71)}…` : s);
118
+ const lines = names.slice(0, SAMPLE).map((name) => {
119
+ const repo = JSON.stringify(clip(local[name] ?? ""));
120
+ const remote = JSON.stringify(clip(server.get(name) ?? ""));
121
+ return ` ${name}\n repo: ${repo}\n tolkit: ${remote}`;
122
+ });
123
+ if (names.length > SAMPLE)
124
+ lines.push(` … (+${names.length - SAMPLE} more)`);
125
+ lines.push(" resolve: edit your source file to match Tolkit, or run `tolkit push --from <file> --update` to keep the repo value");
126
+ return lines.join("\n");
127
+ }
128
+ export function formatTranslationPlan(locale, path, plan) {
129
+ return [
130
+ `${locale} (${path})`,
131
+ formatList("fill", plan.filled),
132
+ formatList("overwrite", plan.overwritten),
133
+ ...(plan.skippedConflicts.length ? [formatList("differs (use --update to overwrite)", plan.skippedConflicts)] : []),
134
+ ...(plan.unknown.length ? [formatList("unknown keys (ignored)", plan.unknown)] : []),
135
+ ` unchanged: ${plan.unchanged}`,
136
+ ].join("\n");
137
+ }
138
+ /** `--locales a,b` → ["a", "b"]; empty/undefined → undefined (all). */
139
+ export function parseLocaleList(raw) {
140
+ const list = (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean);
141
+ return list.length ? list : undefined;
142
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * i18next v21+ plural suffix keys → ICU plurals, for `push --plurals i18next`.
3
+ * `inbox.files_one` + `inbox.files_other` (with `{{count}}`) become one key
4
+ * `inbox.files` = `{count, plural, one {# file} other {# files}}`, which the
5
+ * server stores as a plural key. Groups need an `_other` sibling; anything
6
+ * else is left as it is. Mirrors lib/formatters/plurals.ts on the server.
7
+ */
8
+ const CATEGORIES = ["zero", "one", "two", "few", "many", "other"];
9
+ const SUFFIX_RE = new RegExp(`^(.+)_(${CATEGORIES.join("|")})$`);
10
+ /** Native text → ICU form text: `{{count}}` → `#`, literal `#` quoted. */
11
+ function toForm(text) {
12
+ return text.replace(/'(?=[{}#|])/g, "''").replace(/#/g, "'#'").split("{{count}}").join("#");
13
+ }
14
+ export function groupI18nextPlurals(flat) {
15
+ const groups = new Map();
16
+ for (const [key, value] of Object.entries(flat)) {
17
+ const m = SUFFIX_RE.exec(key);
18
+ if (!m)
19
+ continue;
20
+ const g = groups.get(m[1]) ?? {};
21
+ g[m[2]] = value;
22
+ groups.set(m[1], g);
23
+ }
24
+ const out = {};
25
+ for (const [key, value] of Object.entries(flat)) {
26
+ const m = SUFFIX_RE.exec(key);
27
+ const g = m ? groups.get(m[1]) : undefined;
28
+ if (m && g && g.other !== undefined) {
29
+ if (!(m[1] in out)) {
30
+ const forms = CATEGORIES.filter((c) => g[c] !== undefined).map((c) => `${c} {${toForm(g[c])}}`);
31
+ out[m[1]] = `{count, plural, ${forms.join(" ")}}`;
32
+ }
33
+ continue;
34
+ }
35
+ out[key] = value;
36
+ }
37
+ return out;
38
+ }
@@ -0,0 +1,87 @@
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { globSet, matchesSelfOrAncestor } from "./glob.js";
4
+ /**
5
+ * Which files `tolkit scan` reads. `tolkit.json` may set
6
+ *
7
+ * { "scan": { "include": ["src/**\/*.tsx"], "exclude": ["src/generated"], "prefixes": ["m."] } }
8
+ *
9
+ * `include` replaces the default; `exclude` adds to the always-excluded set;
10
+ * `prefixes` are what code puts before a key name (`m.` for Paraglide).
11
+ * The defaults are source-code extensions only, so locale files themselves
12
+ * (`en.json`, `*.arb`, `*.po`) never count as usages of their own keys.
13
+ */
14
+ export const DEFAULT_INCLUDE = [
15
+ "**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,vue,svelte,astro,html}",
16
+ "**/*.{dart,kt,kts,java,swift,m,mm}",
17
+ "**/*.{py,rb,php,go,cs,cshtml,razor,erb,hbs,liquid,twig,ex,exs,heex}",
18
+ ];
19
+ /** Always skipped, whatever tolkit.json says (dotfiles/dirs too, see below). */
20
+ export const ALWAYS_EXCLUDE = ["node_modules", "dist", ".next", "build", "coverage"];
21
+ // Files bigger than this are generated or vendored, not hand-written source.
22
+ const MAX_FILE_BYTES = 2 * 1024 * 1024;
23
+ /** Read `scan` from a parsed tolkit.json, ignoring anything malformed. */
24
+ export function scanConfigFrom(file) {
25
+ const scan = file?.scan;
26
+ if (!scan || typeof scan !== "object")
27
+ return {};
28
+ const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && !!x.trim()) : undefined;
29
+ const { include, exclude, prefixes } = scan;
30
+ return { include: strings(include), exclude: strings(exclude), prefixes: strings(prefixes) };
31
+ }
32
+ /** Compile a config into the two predicates the walker needs. */
33
+ export function compileScanConfig(cfg, extraExclude = []) {
34
+ const include = globSet(cfg.include?.length ? cfg.include : DEFAULT_INCLUDE);
35
+ const exclude = globSet([...ALWAYS_EXCLUDE, ...(cfg.exclude ?? []), ...extraExclude]);
36
+ const hidden = (path) => path.split("/").some((s) => s.startsWith("."));
37
+ return {
38
+ /** Should the walker enter this directory (root-relative path)? */
39
+ descend: (dir) => !hidden(dir) && !matchesSelfOrAncestor(exclude, dir),
40
+ /** Should this file be read? */
41
+ accept: (file) => !hidden(file) && !matchesSelfOrAncestor(exclude, file) && include.test(file),
42
+ };
43
+ }
44
+ /**
45
+ * Walk `root` in a stable (sorted) order, yielding accepted text files with
46
+ * root-relative forward-slash paths. Unreadable, oversized and binary files
47
+ * are skipped with a warning via `warn`; the walk continues.
48
+ */
49
+ export async function* walkFiles(root, rules, warn = () => { }, isBinary = () => false) {
50
+ async function* walk(rel) {
51
+ let entries;
52
+ try {
53
+ entries = await readdir(join(root, rel), { withFileTypes: true });
54
+ }
55
+ catch (e) {
56
+ warn(`skipped ${rel || "."}: ${e instanceof Error ? e.message : e}`);
57
+ return;
58
+ }
59
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
60
+ for (const ent of entries) {
61
+ const path = rel ? `${rel}/${ent.name}` : ent.name;
62
+ if (ent.isDirectory()) {
63
+ if (rules.descend(path))
64
+ yield* walk(path);
65
+ }
66
+ else if (ent.isFile() && rules.accept(path)) {
67
+ try {
68
+ const abs = join(root, path);
69
+ if ((await stat(abs)).size > MAX_FILE_BYTES) {
70
+ warn(`skipped ${path}: larger than 2 MB`);
71
+ continue;
72
+ }
73
+ const buf = await readFile(abs);
74
+ if (isBinary(buf)) {
75
+ warn(`skipped ${path}: binary`);
76
+ continue;
77
+ }
78
+ yield { path, text: buf.toString("utf8") };
79
+ }
80
+ catch (e) {
81
+ warn(`skipped ${path}: ${e instanceof Error ? e.message : e}`);
82
+ }
83
+ }
84
+ }
85
+ }
86
+ yield* walk("");
87
+ }