@x18n/cli 0.0.2 → 0.0.3
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/dist/cli.d.mts +4 -0
- package/dist/cli.mjs +689 -0
- package/dist/context-Za_ea1Nk.mjs +148 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +1 -0
- package/dist/presets.d.mts +1 -0
- package/dist/presets.mjs +2 -0
- package/dist/ui-Bp3xyqr_.mjs +74 -0
- package/package.json +5 -5
package/dist/cli.d.mts
ADDED
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
import { a as openWorkspace, c as readInput, d as stdinArg, f as useColor, i as exitCodeOf, l as runPlan, n as displayPath, o as out, p as wireDiagnostics, r as errorInfo, s as printJson, t as cwd, u as singleProject } from "./context-Za_ea1Nk.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { PluginFileSchema, X18nError, isJsonObject, parseMessageBatch, placeholderProblems, renderPrompt, toWireRange, validate } from "@x18n/core";
|
|
4
|
+
import process from "node:process";
|
|
5
|
+
import cac from "cac";
|
|
6
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
+
import { dirname, join, resolve } from "node:path";
|
|
8
|
+
import { createInterface } from "node:readline/promises";
|
|
9
|
+
import { configFileNames, findConfigFile, loadWorkspace, migrateI18nAlly } from "@x18n/node";
|
|
10
|
+
import { extractItems, findCandidates, toPlanFile } from "@x18n/builtins/extractors";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { namespaceFromPath } from "@x18n/builtins/finders";
|
|
13
|
+
import { parse, stringify } from "yaml";
|
|
14
|
+
//#region package.json
|
|
15
|
+
var version = "0.0.3";
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/commands/change.ts
|
|
18
|
+
async function project(options) {
|
|
19
|
+
return singleProject(await openWorkspace(options));
|
|
20
|
+
}
|
|
21
|
+
async function set(key, options) {
|
|
22
|
+
if (options.value === void 0) throw new X18nError("X18N4008", "pass --value <text> (or --value - to read stdin)");
|
|
23
|
+
const loaded = await project(options);
|
|
24
|
+
const value = options.value === "\0stdin" ? (await readInput(stdinArg)).replace(/\r?\n$/, "") : String(options.value);
|
|
25
|
+
const locale = options.locale ?? loaded.project.sourceLocale;
|
|
26
|
+
await runPlan("set", loaded, loaded.project.plan([{
|
|
27
|
+
type: "set",
|
|
28
|
+
key: loaded.project.parseKey(key),
|
|
29
|
+
locale,
|
|
30
|
+
value
|
|
31
|
+
}]), options);
|
|
32
|
+
}
|
|
33
|
+
async function apply(source, options) {
|
|
34
|
+
const loaded = await project(options);
|
|
35
|
+
const p = loaded.project;
|
|
36
|
+
let data;
|
|
37
|
+
try {
|
|
38
|
+
data = JSON.parse(await readInput(source));
|
|
39
|
+
} catch (error) {
|
|
40
|
+
throw new X18nError("X18N4008", `${source} is not JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
|
+
}
|
|
42
|
+
const ops = parseMessageBatch(p, data);
|
|
43
|
+
const rejected = placeholderProblems(p, ops);
|
|
44
|
+
if (rejected.length > 0 && !options.force) {
|
|
45
|
+
if (options.json) {
|
|
46
|
+
printJson("apply", {
|
|
47
|
+
applied: false,
|
|
48
|
+
rejected
|
|
49
|
+
}, [], [new X18nError("X18N4007", `${rejected.length} values`).toJSON()]);
|
|
50
|
+
return 1;
|
|
51
|
+
}
|
|
52
|
+
for (const r of rejected) out(`rejected ${r.locale} ${r.key}: ${[r.missing.length ? `missing ${r.missing.join(", ")}` : "", r.extra.length ? `unexpected ${r.extra.join(", ")}` : ""].filter(Boolean).join("; ")}`);
|
|
53
|
+
out(`${rejected.length} values have placeholder problems; nothing was written. Fix them or pass --force.`);
|
|
54
|
+
return 1;
|
|
55
|
+
}
|
|
56
|
+
await runPlan("apply", loaded, p.plan(ops), options);
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
async function rename(from, to, options) {
|
|
60
|
+
const loaded = await project(options);
|
|
61
|
+
const p = loaded.project;
|
|
62
|
+
const op = {
|
|
63
|
+
type: "rename",
|
|
64
|
+
from: p.parseKey(from),
|
|
65
|
+
to: p.parseKey(to),
|
|
66
|
+
usages: options.usages !== false
|
|
67
|
+
};
|
|
68
|
+
await runPlan("rename", loaded, p.plan([op]), options);
|
|
69
|
+
}
|
|
70
|
+
async function remove(key, options) {
|
|
71
|
+
const loaded = await project(options);
|
|
72
|
+
const locales = options.locale === void 0 ? "all" : [options.locale].flat();
|
|
73
|
+
await runPlan("delete", loaded, loaded.project.plan([{
|
|
74
|
+
type: "delete",
|
|
75
|
+
key: loaded.project.parseKey(key),
|
|
76
|
+
locales
|
|
77
|
+
}]), options);
|
|
78
|
+
}
|
|
79
|
+
async function fill(options) {
|
|
80
|
+
const loaded = await project(options);
|
|
81
|
+
const p = loaded.project;
|
|
82
|
+
const targets = options.locale === void 0 ? p.locales.filter((l) => l !== p.sourceLocale) : [options.locale].flat();
|
|
83
|
+
const ops = [];
|
|
84
|
+
for (const locale of targets) for (const key of p.keys({ missing: locale })) {
|
|
85
|
+
if (p.message(key, locale) !== void 0) continue;
|
|
86
|
+
ops.push({
|
|
87
|
+
type: "set",
|
|
88
|
+
key,
|
|
89
|
+
locale,
|
|
90
|
+
value: options.copySource ? p.message(key, p.sourceLocale)?.value ?? "" : ""
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
await runPlan("fill", loaded, p.plan(ops), options);
|
|
94
|
+
}
|
|
95
|
+
async function format(options) {
|
|
96
|
+
const loaded = await project(options);
|
|
97
|
+
await runPlan("format", loaded, loaded.project.plan([{ type: "format" }]), options);
|
|
98
|
+
}
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/commands/check.ts
|
|
101
|
+
function list(value) {
|
|
102
|
+
return value === void 0 ? [] : [value].flat().flatMap((item) => String(item).split(",")).map((item) => item.trim()).filter(Boolean);
|
|
103
|
+
}
|
|
104
|
+
function filterDiagnostics(diagnostics, options) {
|
|
105
|
+
const locales = list(options.locale);
|
|
106
|
+
const only = list(options.only);
|
|
107
|
+
const skip = list(options.skip);
|
|
108
|
+
return diagnostics.filter((d) => locales.length === 0 || d.locale === void 0 || locales.includes(d.locale) || d.code === "missing-translation" && locales.some((l) => d.message.includes(l))).filter((d) => only.length === 0 || only.includes(d.code)).filter((d) => !skip.includes(d.code)).map((d) => options.strict && d.severity === "warning" ? {
|
|
109
|
+
...d,
|
|
110
|
+
severity: "error"
|
|
111
|
+
} : d);
|
|
112
|
+
}
|
|
113
|
+
function reportInputs(workspace, options) {
|
|
114
|
+
return workspace.projects.map((loaded) => {
|
|
115
|
+
const analysis = loaded.project.analyze();
|
|
116
|
+
const diagnostics = filterDiagnostics(analysis.diagnostics, options);
|
|
117
|
+
return {
|
|
118
|
+
project: loaded.name,
|
|
119
|
+
text: (path) => loaded.project.text(path),
|
|
120
|
+
diagnostics,
|
|
121
|
+
coverage: analysis.coverage,
|
|
122
|
+
summary: {
|
|
123
|
+
errors: diagnostics.filter((d) => d.severity === "error").length,
|
|
124
|
+
warnings: diagnostics.filter((d) => d.severity === "warning").length,
|
|
125
|
+
infos: diagnostics.filter((d) => d.severity === "info" || d.severity === "hint").length,
|
|
126
|
+
files: new Set(diagnostics.flatMap((d) => d.location ? [d.location.path] : [])).size
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
async function report(workspace, options) {
|
|
132
|
+
const inputs = reportInputs(workspace, options);
|
|
133
|
+
const reporterIds = list(options.reporter);
|
|
134
|
+
const ids = reporterIds.length ? reporterIds : [options.json ? "json" : "pretty"];
|
|
135
|
+
const outputs = list(options.output);
|
|
136
|
+
const available = workspace.projects[0]?.project.reporters ?? /* @__PURE__ */ new Map();
|
|
137
|
+
const roots = new Map(workspace.projects.map((p) => [p.name, p.root]));
|
|
138
|
+
for (const [i, id] of ids.entries()) {
|
|
139
|
+
const reporter = available.get(id);
|
|
140
|
+
if (!reporter) throw new X18nError("X18N0001", `unknown reporter "${id}" (${[...available.keys()].join(", ")})`);
|
|
141
|
+
const text = await reporter.report(inputs, {
|
|
142
|
+
color: !outputs[i] && useColor(options) && id === "pretty",
|
|
143
|
+
displayPath: (path, project) => displayPath(roots.get(project) ?? "", path)
|
|
144
|
+
});
|
|
145
|
+
if (outputs[i]) await writeFile(outputs[i], text);
|
|
146
|
+
else if (text) process.stdout.write(text);
|
|
147
|
+
}
|
|
148
|
+
const errors = inputs.reduce((sum, input) => sum + input.summary.errors, 0);
|
|
149
|
+
const warnings = inputs.reduce((sum, input) => sum + input.summary.warnings, 0);
|
|
150
|
+
const tooManyWarnings = options.maxWarnings !== void 0 && warnings > Number(options.maxWarnings);
|
|
151
|
+
return errors > 0 || tooManyWarnings ? 1 : 0;
|
|
152
|
+
}
|
|
153
|
+
async function check(options) {
|
|
154
|
+
const workspace = await openWorkspace(options);
|
|
155
|
+
const code = await report(workspace, options);
|
|
156
|
+
if (!options.watch) return code;
|
|
157
|
+
const rerun = async () => {
|
|
158
|
+
if (process.stdout.isTTY) process.stdout.write("\x1Bc");
|
|
159
|
+
out(`[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] File change detected. Checking...\n`);
|
|
160
|
+
await report(workspace, options);
|
|
161
|
+
};
|
|
162
|
+
for (const loaded of workspace.projects) {
|
|
163
|
+
loaded.project.watch();
|
|
164
|
+
loaded.project.onChange(() => void rerun());
|
|
165
|
+
}
|
|
166
|
+
out("\nWatching for file changes.");
|
|
167
|
+
return new Promise(() => {});
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/commands/extract.ts
|
|
171
|
+
function isPlanItem(value) {
|
|
172
|
+
if (!isJsonObject(value) || !isJsonObject(value.range)) return false;
|
|
173
|
+
return [
|
|
174
|
+
"path",
|
|
175
|
+
"original",
|
|
176
|
+
"key",
|
|
177
|
+
"value",
|
|
178
|
+
"replacement"
|
|
179
|
+
].every((field) => typeof value[field] === "string") && typeof value.range.start === "number" && typeof value.range.end === "number" && Array.isArray(value.imports) && value.imports.every((line) => typeof line === "string");
|
|
180
|
+
}
|
|
181
|
+
async function readPlan(file) {
|
|
182
|
+
const data = JSON.parse(await readFile(file, "utf8"));
|
|
183
|
+
if (!isJsonObject(data) || !Array.isArray(data.items) || !data.items.every(isPlanItem)) throw new X18nError("X18N4008", `${file} is not an extraction plan`);
|
|
184
|
+
return data.items;
|
|
185
|
+
}
|
|
186
|
+
/** One question per string in a TTY: extract with the proposed key, a typed key, or skip. */
|
|
187
|
+
async function review(candidates, root) {
|
|
188
|
+
const rl = createInterface({
|
|
189
|
+
input: process.stdin,
|
|
190
|
+
output: process.stderr
|
|
191
|
+
});
|
|
192
|
+
const picked = [];
|
|
193
|
+
try {
|
|
194
|
+
for (const candidate of candidates) {
|
|
195
|
+
process.stderr.write(`\n${displayPath(root, candidate.path)}:${candidate.line} ${JSON.stringify(candidate.text)}\n → ${candidate.replacement}\n`);
|
|
196
|
+
const reply = (await rl.question(`Extract as "${candidate.key}"? [Y/n/key/q] `)).trim();
|
|
197
|
+
if (reply === "q") break;
|
|
198
|
+
if (reply === "n") continue;
|
|
199
|
+
picked.push(reply && reply !== "y" ? {
|
|
200
|
+
...candidate,
|
|
201
|
+
key: reply,
|
|
202
|
+
replacement: candidate.replacement.replace(candidate.key, reply)
|
|
203
|
+
} : candidate);
|
|
204
|
+
}
|
|
205
|
+
} finally {
|
|
206
|
+
rl.close();
|
|
207
|
+
}
|
|
208
|
+
return picked;
|
|
209
|
+
}
|
|
210
|
+
async function extract(files, options) {
|
|
211
|
+
const loaded = singleProject(await openWorkspace(options));
|
|
212
|
+
const { project } = loaded;
|
|
213
|
+
if (options.apply) {
|
|
214
|
+
const items = extractItems(project, await readPlan(options.apply));
|
|
215
|
+
await runPlan("extract", loaded, project.plan([{
|
|
216
|
+
type: "extract",
|
|
217
|
+
items
|
|
218
|
+
}]), options);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
const candidates = findCandidates(project, { files });
|
|
222
|
+
if (options.plan) {
|
|
223
|
+
await writeFile(options.plan, `${JSON.stringify(toPlanFile(project, candidates), null, 2)}\n`);
|
|
224
|
+
if (options.json) printJson("extract", {
|
|
225
|
+
plan: options.plan,
|
|
226
|
+
items: candidates.length
|
|
227
|
+
});
|
|
228
|
+
else out(`Wrote ${candidates.length} strings to ${options.plan}. Edit keys and replacements, then run \`x18n extract --apply ${options.plan}\`.`);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const interactive = !options.list && !options.yes && !options.json && process.stdin.isTTY;
|
|
232
|
+
if (options.list || !interactive && !options.yes) {
|
|
233
|
+
if (options.json) {
|
|
234
|
+
printJson("extract", { items: candidates.map((c) => ({
|
|
235
|
+
...c,
|
|
236
|
+
file: displayPath(loaded.root, c.path)
|
|
237
|
+
})) });
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
for (const c of candidates) out(`${displayPath(loaded.root, c.path)}:${c.line}\t${c.kind}\t${JSON.stringify(c.text)}\t→ ${c.key}${c.reused ? " (existing)" : ""}`);
|
|
241
|
+
out(`${candidates.length} strings. Apply with \`x18n extract --yes\`, or review with \`x18n extract --plan plan.json\`.`);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const chosen = interactive ? await review(candidates, loaded.root) : candidates;
|
|
245
|
+
if (chosen.length === 0) {
|
|
246
|
+
out("Nothing to extract.");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
await runPlan("extract", loaded, project.plan([{
|
|
250
|
+
type: "extract",
|
|
251
|
+
items: extractItems(project, chosen)
|
|
252
|
+
}]), options);
|
|
253
|
+
}
|
|
254
|
+
//#endregion
|
|
255
|
+
//#region src/commands/look.ts
|
|
256
|
+
function percent(coverage) {
|
|
257
|
+
return coverage.total === 0 ? 100 : Math.floor(coverage.translated / coverage.total * 1e3) / 10;
|
|
258
|
+
}
|
|
259
|
+
function summaryOf(loaded) {
|
|
260
|
+
const diagnostics = loaded.project.analyze().diagnostics;
|
|
261
|
+
return {
|
|
262
|
+
errors: diagnostics.filter((d) => d.severity === "error").length,
|
|
263
|
+
warnings: diagnostics.filter((d) => d.severity === "warning").length,
|
|
264
|
+
infos: diagnostics.filter((d) => d.severity === "info" || d.severity === "hint").length
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
function statusData(loaded) {
|
|
268
|
+
const { project } = loaded;
|
|
269
|
+
return {
|
|
270
|
+
name: loaded.name,
|
|
271
|
+
root: displayPath(loaded.root, ""),
|
|
272
|
+
sourceLocale: project.sourceLocale,
|
|
273
|
+
locales: project.analyze().coverage.map((c) => ({
|
|
274
|
+
locale: c.locale,
|
|
275
|
+
total: c.total,
|
|
276
|
+
translated: c.translated,
|
|
277
|
+
missing: c.missing.length,
|
|
278
|
+
empty: c.empty.length,
|
|
279
|
+
percent: percent(c)
|
|
280
|
+
})),
|
|
281
|
+
resources: project.resources.length,
|
|
282
|
+
keys: project.keys().length,
|
|
283
|
+
usages: project.usages().length,
|
|
284
|
+
summary: summaryOf(loaded)
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
async function status(options) {
|
|
288
|
+
const workspace = await openWorkspace(options);
|
|
289
|
+
if (options.json) {
|
|
290
|
+
printJson("status", { projects: workspace.projects.map(statusData) });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
for (const loaded of workspace.projects) {
|
|
294
|
+
const { project } = loaded;
|
|
295
|
+
const summary = summaryOf(loaded);
|
|
296
|
+
out(`${loaded.name} (${displayPath(loaded.root, "")})`);
|
|
297
|
+
out(` ${project.resources.length} resources, ${project.keys().length} keys, ${project.usages().length} usages`);
|
|
298
|
+
for (const c of project.analyze().coverage) {
|
|
299
|
+
const label = `${c.locale}${c.locale === project.sourceLocale ? " (source)" : ""}`;
|
|
300
|
+
out(` ${label.padEnd(16)} ${String(percent(c)).padStart(5)}% ${c.translated}/${c.total}${c.missing.length ? `, ${c.missing.length} missing` : ""}${c.empty.length ? `, ${c.empty.length} empty` : ""}`);
|
|
301
|
+
}
|
|
302
|
+
out(` ${summary.errors} errors, ${summary.warnings} warnings`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** One page of a list: `--limit` items from `--cursor`, plus the cursor of the next page. */
|
|
306
|
+
function page(items, options) {
|
|
307
|
+
const start = Number(options.cursor ?? 0) || 0;
|
|
308
|
+
const end = options.limit ? start + Number(options.limit) : items.length;
|
|
309
|
+
return {
|
|
310
|
+
items: items.slice(start, end),
|
|
311
|
+
total: items.length,
|
|
312
|
+
nextCursor: end < items.length ? String(end) : void 0
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
async function keys(glob, options) {
|
|
316
|
+
const workspace = await openWorkspace(options);
|
|
317
|
+
const projects = workspace.projects.map((loaded) => {
|
|
318
|
+
const { project } = loaded;
|
|
319
|
+
const { items, total, nextCursor } = page(project.keys({
|
|
320
|
+
glob,
|
|
321
|
+
missing: options.missing,
|
|
322
|
+
unused: options.unused,
|
|
323
|
+
namespace: options.namespace
|
|
324
|
+
}), options);
|
|
325
|
+
const values = (key) => Object.fromEntries(project.locales.map((locale) => [locale, project.message(key, locale)?.value]));
|
|
326
|
+
return {
|
|
327
|
+
name: loaded.name,
|
|
328
|
+
total,
|
|
329
|
+
nextCursor,
|
|
330
|
+
keys: items.map((key) => options.values ? {
|
|
331
|
+
key,
|
|
332
|
+
values: values(key)
|
|
333
|
+
} : { key })
|
|
334
|
+
};
|
|
335
|
+
});
|
|
336
|
+
if (options.json) {
|
|
337
|
+
printJson("keys", { projects });
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
for (const p of projects) {
|
|
341
|
+
if (workspace.projects.length > 1) out(`# ${p.name}`);
|
|
342
|
+
for (const item of p.keys) out("values" in item ? `${item.key}\t${JSON.stringify(item.values)}` : item.key);
|
|
343
|
+
if (p.nextCursor) out(`… ${p.total - Number(p.nextCursor)} more (--cursor ${p.nextCursor})`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function locate(loaded, path, start, end) {
|
|
347
|
+
const range = toWireRange(loaded.project.text(path), start, end);
|
|
348
|
+
return {
|
|
349
|
+
file: displayPath(loaded.root, path),
|
|
350
|
+
line: range.line,
|
|
351
|
+
column: range.column
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
async function get(input, options) {
|
|
355
|
+
const workspace = await openWorkspace(options);
|
|
356
|
+
const projects = workspace.projects.flatMap((loaded) => {
|
|
357
|
+
const { project } = loaded;
|
|
358
|
+
const info = project.get(project.parseKey(input));
|
|
359
|
+
if (!info) return [];
|
|
360
|
+
const resourceOf = (id) => project.resources.find((r) => r.id === id)?.path ?? id;
|
|
361
|
+
return [{
|
|
362
|
+
name: loaded.name,
|
|
363
|
+
key: info.key,
|
|
364
|
+
namespace: info.namespace,
|
|
365
|
+
messages: info.messages.map((m) => ({
|
|
366
|
+
locale: m.locale,
|
|
367
|
+
value: m.value,
|
|
368
|
+
...locate(loaded, resourceOf(m.resource), m.range?.key.start ?? 0, m.range?.key.end ?? 0)
|
|
369
|
+
})),
|
|
370
|
+
missing: info.missing,
|
|
371
|
+
usages: info.usages.map((u) => ({
|
|
372
|
+
possible: u.possible,
|
|
373
|
+
raw: u.usage.raw,
|
|
374
|
+
...locate(loaded, u.usage.path, u.usage.range.start, u.usage.range.end)
|
|
375
|
+
})),
|
|
376
|
+
diagnostics: wireDiagnostics(loaded, info.diagnostics)
|
|
377
|
+
}];
|
|
378
|
+
});
|
|
379
|
+
if (options.json) {
|
|
380
|
+
printJson("get", { projects });
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (projects.length === 0) out(`"${input}" is not defined.`);
|
|
384
|
+
for (const p of projects) {
|
|
385
|
+
out(`${p.key}${workspace.projects.length > 1 ? ` (${p.name})` : ""}`);
|
|
386
|
+
for (const m of p.messages) out(` ${m.locale.padEnd(8)} ${JSON.stringify(m.value)} ${m.file}:${m.line}:${m.column}`);
|
|
387
|
+
if (p.missing.length) out(` missing in ${p.missing.join(", ")}`);
|
|
388
|
+
out(` ${p.usages.length} usages`);
|
|
389
|
+
for (const u of p.usages) out(` ${u.file}:${u.line}:${u.column}${u.possible ? " (possible)" : ""}`);
|
|
390
|
+
for (const d of p.diagnostics) out(` ${d.severity} ${d.code}: ${d.message}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
async function usages(input, options) {
|
|
394
|
+
const projects = (await openWorkspace(options)).projects.map((loaded) => {
|
|
395
|
+
const { project } = loaded;
|
|
396
|
+
const { items, total, nextCursor } = page(project.usages({
|
|
397
|
+
key: input === void 0 ? void 0 : project.parseKey(input),
|
|
398
|
+
path: options.file
|
|
399
|
+
}), options);
|
|
400
|
+
return {
|
|
401
|
+
name: loaded.name,
|
|
402
|
+
total,
|
|
403
|
+
nextCursor,
|
|
404
|
+
usages: items.map((m) => ({
|
|
405
|
+
key: m.usage.key,
|
|
406
|
+
raw: m.usage.raw,
|
|
407
|
+
possible: m.possible,
|
|
408
|
+
dynamic: m.usage.dynamic,
|
|
409
|
+
...locate(loaded, m.usage.path, m.usage.range.start, m.usage.range.end)
|
|
410
|
+
}))
|
|
411
|
+
};
|
|
412
|
+
});
|
|
413
|
+
if (options.json) {
|
|
414
|
+
printJson("usages", { projects });
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
for (const p of projects) for (const u of p.usages) out(`${u.file}:${u.line}:${u.column}\t${u.key ?? u.raw}${u.possible ? " (possible)" : ""}`);
|
|
418
|
+
}
|
|
419
|
+
async function locales(options) {
|
|
420
|
+
const projects = (await openWorkspace(options)).projects.map((loaded) => ({
|
|
421
|
+
name: loaded.name,
|
|
422
|
+
sourceLocale: loaded.project.sourceLocale,
|
|
423
|
+
locales: loaded.project.locales.map((code) => ({
|
|
424
|
+
...loaded.project.localeInfo(code),
|
|
425
|
+
resources: loaded.project.resources.filter((r) => r.locale === code).map((r) => displayPath(loaded.root, r.path))
|
|
426
|
+
}))
|
|
427
|
+
}));
|
|
428
|
+
if (options.json) {
|
|
429
|
+
printJson("locales", { projects });
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
for (const p of projects) for (const l of p.locales) out(`${l.code.padEnd(10)} ${(l.displayName ?? "").padEnd(28)} ${l.resources.join(", ")}`);
|
|
433
|
+
}
|
|
434
|
+
async function doctor(options) {
|
|
435
|
+
const projects = (await openWorkspace(options)).projects.map((loaded) => ({
|
|
436
|
+
...loaded.project.explain(),
|
|
437
|
+
root: displayPath(loaded.root, ""),
|
|
438
|
+
configFile: loaded.configFile && displayPath(loaded.configFile, "")
|
|
439
|
+
}));
|
|
440
|
+
if (options.json) {
|
|
441
|
+
printJson("doctor", { projects });
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
for (const e of projects) {
|
|
445
|
+
out(`# ${e.name} (${e.root})`);
|
|
446
|
+
out(`config: ${e.configFile ?? "none (detection only)"}`);
|
|
447
|
+
out(`presets:`);
|
|
448
|
+
const applied = e.presets.filter((p) => p.reason === "detected" || p.reason === "listed");
|
|
449
|
+
for (const p of applied) out(` ✓ ${p.name} (${p.reason})`);
|
|
450
|
+
if (applied.length === 0) out(" none");
|
|
451
|
+
if (e.presets.length > applied.length) out(` ${e.presets.length - applied.length} others not applied (--json lists them)`);
|
|
452
|
+
out("finders:");
|
|
453
|
+
for (const f of e.finders) out(` ${f.id}: ${f.resources.length} resources${f.resources.length ? `\n ${f.resources.slice(0, 20).join("\n ")}` : ""}`);
|
|
454
|
+
out("formats:");
|
|
455
|
+
for (const f of e.formats.filter((f) => f.resources > 0)) out(` ${f.id} (${f.extensions.join(", ")}): ${f.resources} resources`);
|
|
456
|
+
out("scanners:");
|
|
457
|
+
for (const s of e.scanners) out(` ${s.id} (${s.extensions.join(", ") || "none"}): ${s.files} files`);
|
|
458
|
+
if (e.conflicts.length) out(`conflicts:\n${e.conflicts.map((c) => ` .${c.extension}: ${c.winner} wins over ${c.loser}`).join("\n")}`);
|
|
459
|
+
if (e.errors.length) out(`errors:\n${e.errors.map((err) => ` ${err.code} ${err.message}`).join("\n")}`);
|
|
460
|
+
out("config origins:");
|
|
461
|
+
for (const [key, origin] of Object.entries(e.config.origins)) out(` ${key}: ${origin}`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
//#endregion
|
|
465
|
+
//#region src/commands/migrate.ts
|
|
466
|
+
async function migrate(source, options) {
|
|
467
|
+
if (source !== "i18n-ally") throw new X18nError("X18N0001", `unknown migration source "${source}" (i18n-ally)`);
|
|
468
|
+
const root = resolve(options.root ?? cwd());
|
|
469
|
+
const result = await migrateI18nAlly(root, { format: options.format });
|
|
470
|
+
const existing = findConfigFile(root);
|
|
471
|
+
if (existing && !options.force && !options.dryRun && result.files.length > 0) throw new X18nError("X18N0001", `${existing} already exists (pass --force to replace it)`);
|
|
472
|
+
if (!options.dryRun) for (const file of result.files) {
|
|
473
|
+
const path = join(root, file.path);
|
|
474
|
+
await mkdir(dirname(path), { recursive: true });
|
|
475
|
+
if (file.path === ".x18n/reviews.yml" && existsSync(path)) continue;
|
|
476
|
+
await writeFile(path, file.content);
|
|
477
|
+
}
|
|
478
|
+
if (options.json) {
|
|
479
|
+
printJson("migrate", {
|
|
480
|
+
...result,
|
|
481
|
+
written: !options.dryRun
|
|
482
|
+
});
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
for (const file of result.files) out(options.dryRun ? `--- ${file.path}\n${file.content}` : `wrote ${file.path}`);
|
|
486
|
+
for (const note of result.notes) out(`note: ${note}`);
|
|
487
|
+
if (result.removable.length) out(`These i18n-ally settings can be removed now:\n${result.removable.map((key) => ` ${key}`).join("\n")}`);
|
|
488
|
+
}
|
|
489
|
+
//#endregion
|
|
490
|
+
//#region src/commands/prompt.ts
|
|
491
|
+
async function prompt(kind, options) {
|
|
492
|
+
if (kind !== "translate" && kind !== "review") throw new X18nError("X18N0001", `unknown prompt "${kind}" (translate, review)`);
|
|
493
|
+
const locale = kind === "translate" ? options.to : options.locale ?? options.to;
|
|
494
|
+
if (!locale) throw new X18nError("X18N0001", kind === "translate" ? "pass --to <locale>" : "pass --locale <locale>");
|
|
495
|
+
const { project } = singleProject(await openWorkspace(options));
|
|
496
|
+
const data = project.prompt(kind, locale, {
|
|
497
|
+
keys: options.keys,
|
|
498
|
+
namespace: options.namespace,
|
|
499
|
+
limit: options.limit === void 0 ? void 0 : Number(options.limit),
|
|
500
|
+
cursor: options.cursor,
|
|
501
|
+
context: options.context
|
|
502
|
+
});
|
|
503
|
+
if (options.json || options.format === "json") printJson(`prompt ${kind}`, data);
|
|
504
|
+
else out(renderPrompt(data));
|
|
505
|
+
}
|
|
506
|
+
//#endregion
|
|
507
|
+
//#region src/commands/setup.ts
|
|
508
|
+
async function schema(name, options) {
|
|
509
|
+
const which = name ?? "config";
|
|
510
|
+
if (which !== "config" && which !== "plugin") throw new X18nError("X18N0001", `unknown schema "${which}" (config, plugin)`);
|
|
511
|
+
const require = createRequire(import.meta.url);
|
|
512
|
+
const text = await readFile(require.resolve(`@x18n/core/schema/${which}.json`), "utf8");
|
|
513
|
+
if (options.json) printJson("schema", {
|
|
514
|
+
name: which,
|
|
515
|
+
schema: JSON.parse(text)
|
|
516
|
+
});
|
|
517
|
+
else out(text);
|
|
518
|
+
}
|
|
519
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
520
|
+
/** The folders and file name that name `namespace`, in the style of `namespace.fromPath`. */
|
|
521
|
+
function namespaceSpan(parts, namespace, fromPath) {
|
|
522
|
+
for (let start = 0; start < parts.length; start++) for (let end = start + 1; end <= parts.length; end++) if (namespaceFromPath(parts.slice(start, end).join("/"), fromPath) === namespace) return {
|
|
523
|
+
start,
|
|
524
|
+
end
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
/** The resource pattern that matches a found file: `public/locales/en/common.json` → `public/locales/{locale}/{namespaces}.{ext}`. */
|
|
528
|
+
function patternOf(resource, fromPath) {
|
|
529
|
+
const parts = resource.path.replace(/\.[^./]+$/, "").split("/");
|
|
530
|
+
const span = resource.namespace === void 0 ? void 0 : namespaceSpan(parts, resource.namespace, fromPath);
|
|
531
|
+
if (span) parts.splice(span.start, span.end - span.start, "{namespaces}");
|
|
532
|
+
return `${parts.join("/")}.{ext}`.replace(new RegExp(`(^|[/._-])${escapeRegExp(resource.locale)}(?=[/._-])`), "$1{locale}");
|
|
533
|
+
}
|
|
534
|
+
async function init(options) {
|
|
535
|
+
const root = resolve(options.root ?? cwd());
|
|
536
|
+
const existing = findConfigFile(root);
|
|
537
|
+
if (existing && !options.force) throw new X18nError("X18N0001", `${existing} already exists (pass --force to replace it)`);
|
|
538
|
+
const { project } = (await loadWorkspace({
|
|
539
|
+
cwd: root,
|
|
540
|
+
cache: false
|
|
541
|
+
})).projects[0];
|
|
542
|
+
const detected = project.explain().presets.filter((p) => p.reason === "detected" && p.name !== "general").map((p) => p.name);
|
|
543
|
+
const resources = [...new Set(project.resources.filter((r) => !r.block).map((r) => patternOf(r, project.config.namespace.fromPath)))];
|
|
544
|
+
const config = {
|
|
545
|
+
sourceLocale: project.sourceLocale,
|
|
546
|
+
resources: resources.map((pattern) => ({ pattern }))
|
|
547
|
+
};
|
|
548
|
+
const format = options.format ?? "ts";
|
|
549
|
+
let file;
|
|
550
|
+
let content;
|
|
551
|
+
if (format === "yml" || format === "yaml") {
|
|
552
|
+
file = join(root, "x18n.config.yml");
|
|
553
|
+
content = `# yaml-language-server: $schema=https://x18n.antfu.dev/schema/config.json\n${stringify(config)}`;
|
|
554
|
+
} else if (format === "json") {
|
|
555
|
+
file = join(root, "x18n.config.json");
|
|
556
|
+
content = `${JSON.stringify({
|
|
557
|
+
$schema: "https://x18n.antfu.dev/schema/config.json",
|
|
558
|
+
...config
|
|
559
|
+
}, null, 2)}\n`;
|
|
560
|
+
} else {
|
|
561
|
+
file = join(root, "x18n.config.ts");
|
|
562
|
+
const body = JSON.stringify(config, null, 2).replace(/"(\w+)":/g, "$1:").replace(/"/g, "'");
|
|
563
|
+
content = `import { defineConfig } from '@x18n/core'\n\n// Detected presets: ${detected.join(", ") || "none"}. They apply automatically.\nexport default defineConfig(${body})\n`;
|
|
564
|
+
}
|
|
565
|
+
if (!configFileNames.some((name) => file.endsWith(name))) throw new X18nError("X18N0001", `unknown format "${format}" (ts, yml, json)`);
|
|
566
|
+
await writeFile(file, content);
|
|
567
|
+
if (options.json) printJson("init", {
|
|
568
|
+
file,
|
|
569
|
+
presets: detected,
|
|
570
|
+
config
|
|
571
|
+
});
|
|
572
|
+
else out(`Wrote ${file}\nDetected presets: ${detected.join(", ") || "none"}\nLocales: ${project.locales.join(", ")}`);
|
|
573
|
+
}
|
|
574
|
+
const literal = (value) => JSON.stringify(value, null, 2).replace(/"([a-z_$][\w$]*)":/gi, "$1:");
|
|
575
|
+
/** The TS plugin equivalent of a YAML plugin, using the same built-in factories. */
|
|
576
|
+
function ejectPlugin(data) {
|
|
577
|
+
const lines = [];
|
|
578
|
+
const configLines = [];
|
|
579
|
+
if (data.config) configLines.push(` Object.assign(config, ${literal(data.config).replace(/\n/g, "\n ")})`);
|
|
580
|
+
if (data.scanners?.calls || data.scanners?.regex) {
|
|
581
|
+
configLines.push(` config.usage = {`, ` ...config.usage,`);
|
|
582
|
+
if (data.scanners.calls) configLines.push(` calls: [...config.usage.calls, ...${literal(data.scanners.calls).replace(/\n/g, "\n ")}],`);
|
|
583
|
+
if (data.scanners.regex) configLines.push(` regex: [...config.usage.regex, ...${literal(data.scanners.regex).replace(/\n/g, "\n ")}],`);
|
|
584
|
+
configLines.push(` }`);
|
|
585
|
+
}
|
|
586
|
+
const fields = [` name: ${literal(data.name)},`];
|
|
587
|
+
if (configLines.length) fields.push(` config(config) {`, ...configLines, ` },`);
|
|
588
|
+
if (data.derivedKeys) fields.push(` derivedKeys: ${literal(data.derivedKeys)},`);
|
|
589
|
+
if (data.placeholders) fields.push(` placeholders: ${literal(data.placeholders)}.map(placeholderFromShape),`);
|
|
590
|
+
if (data.normalizeKey) {
|
|
591
|
+
const rules = data.normalizeKey.map((rule) => `.replace(new RegExp(${literal(rule.replace.pattern)}, 'g'), ${literal(rule.replace.with)})`).join("");
|
|
592
|
+
fields.push(` normalizeKey: raw => raw${rules},`);
|
|
593
|
+
}
|
|
594
|
+
if (data.localeInfo) fields.push(` localeInfo: code => (${literal(data.localeInfo)} as Record<string, { flag?: string, displayName?: string }>)[code],`);
|
|
595
|
+
const imports = ["definePlugin", ...data.detect ? ["definePreset"] : []];
|
|
596
|
+
lines.push(`import { ${imports.join(", ")} } from '@x18n/core'`);
|
|
597
|
+
if (data.placeholders) lines.push(`import { placeholderFromShape } from '@x18n/builtins/placeholders'`);
|
|
598
|
+
if (data.scopes) lines.push(`import { regexScopes } from '@x18n/builtins/scanners'`);
|
|
599
|
+
lines.push("", `const plugin = definePlugin({`, ...fields, `})`, "");
|
|
600
|
+
const plugins = `[plugin${data.scopes ? `, regexScopes(${literal(data.scopes.regex)})` : ""}]`;
|
|
601
|
+
if (data.detect) {
|
|
602
|
+
const any = data.detect.dependencies?.any;
|
|
603
|
+
lines.push(`export default definePreset({`, ` name: ${literal(data.name)},`, ...data.exclusive ? [` exclusive: true,`] : [], ` detect: ctx => ${any ? `ctx.hasAnyDependency(${literal(any)})` : "true"},`, ` plugins: ${plugins},`, `})`);
|
|
604
|
+
} else lines.push(data.scopes ? `export default ${plugins}` : "export default plugin");
|
|
605
|
+
return `${lines.join("\n")}\n`;
|
|
606
|
+
}
|
|
607
|
+
async function eject(file, options) {
|
|
608
|
+
const path = resolve(cwd(), file);
|
|
609
|
+
if (!existsSync(path)) throw new X18nError("X18N1001", path);
|
|
610
|
+
const result = validate(PluginFileSchema, parse(await readFile(path, "utf8")));
|
|
611
|
+
if (!result.success) throw new X18nError("X18N1004", result.issues.map((i) => `${i.path}: ${i.message}`).join("; "));
|
|
612
|
+
const code = ejectPlugin(result.output);
|
|
613
|
+
if (options.json) printJson("plugin eject", {
|
|
614
|
+
file: path,
|
|
615
|
+
code
|
|
616
|
+
});
|
|
617
|
+
else out(code);
|
|
618
|
+
}
|
|
619
|
+
//#endregion
|
|
620
|
+
//#region src/cli.ts
|
|
621
|
+
const uiCommands = () => import("./ui-Bp3xyqr_.mjs");
|
|
622
|
+
/** Runs a command and turns errors into the JSON envelope or a printed hint, with the matching exit code. */
|
|
623
|
+
function run(command, action) {
|
|
624
|
+
return async (...args) => {
|
|
625
|
+
const options = args.at(-1);
|
|
626
|
+
try {
|
|
627
|
+
const code = await action(...args);
|
|
628
|
+
process.exitCode = code ?? 0;
|
|
629
|
+
} catch (error) {
|
|
630
|
+
const info = errorInfo(error);
|
|
631
|
+
if (options.json) printJson(command, null, [], [info]);
|
|
632
|
+
else {
|
|
633
|
+
process.stderr.write(`error ${info.code}: ${info.message}\n`);
|
|
634
|
+
if (info.hint) process.stderr.write(` ${info.hint}\n`);
|
|
635
|
+
if (!(error instanceof Error && "code" in error) && error instanceof Error && process.env.DEBUG) process.stderr.write(`${error.stack}\n`);
|
|
636
|
+
}
|
|
637
|
+
process.exitCode = exitCodeOf(error);
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
function createCli() {
|
|
642
|
+
const cli = cac("x18n");
|
|
643
|
+
cli.option("--root <dir>", "Project root (default: nearest config upward from the cwd)").option("--config <file>", "Explicit config file").option("--project <name>", "Pick one project in a monorepo").option("--json", "Print the JSON contract instead of human output").option("--no-cache", "Ignore the persistent cache").option("--yes", "Accept default answers for decisions");
|
|
644
|
+
cli.command("", "Show the status and the main commands").action(run("status", async (options) => {
|
|
645
|
+
await status(options);
|
|
646
|
+
if (!options.json) process.stdout.write("\nCommands: check, keys, get, usages, set, apply, rename, delete, fill, prompt translate, ui. Run `x18n --help` for all.\n");
|
|
647
|
+
}));
|
|
648
|
+
cli.command("status", "Locales with coverage, resources, keys and diagnostics").action(run("status", status));
|
|
649
|
+
cli.command("keys [glob]", "List keys").option("--missing <locale>", "Only keys missing or empty in a locale").option("--unused", "Only keys without usages").option("--namespace <ns>", "Only keys of a namespace").option("--values", "Include the value per locale").option("--limit <n>", "Page size").option("--cursor <cursor>", "Start of the page (from `nextCursor`)").action(run("keys", keys));
|
|
650
|
+
cli.command("get <key>", "Values, resources, usages and diagnostics of one key").action(run("get", get));
|
|
651
|
+
cli.command("usages [key]", "Usages of a key, or all usages").option("--file <path>", "Only usages in a file").option("--limit <n>", "Page size").option("--cursor <cursor>", "Start of the page").action(run("usages", usages));
|
|
652
|
+
cli.command("locales", "Locale codes as found, with display names and resources").action(run("locales", locales));
|
|
653
|
+
cli.command("doctor", "How the project was understood: presets, finders, formats, scanners, config origins").action(run("doctor", doctor));
|
|
654
|
+
cli.command("check", "Report invalid, untranslated and unused keys, like `tsc --noEmit`").option("--watch", "Re-check on change").option("--strict", "Turn every warning into an error").option("--locale <locale>", "Only report for these locales (repeatable)").option("--only <checks>", "Only these check ids (comma separated)").option("--skip <checks>", "Skip these check ids (comma separated)").option("--max-warnings <n>", "Fail when there are more warnings").option("--reporter <id>", "pretty, json, markdown, github or sarif (repeatable)").option("--output <file>", "Write the matching reporter output to a file (repeatable)").action(run("check", check));
|
|
655
|
+
cli.command("set <key>", "Set one value").option("--locale <locale>", "Locale (default: source locale)").option("--value <value>", "The value; `-` reads stdin").option("--dry-run", "Print the plan instead of writing").action(run("set", set));
|
|
656
|
+
cli.command("apply <file>", "Batch set from JSON `{ \"<locale>\": { \"<key>\": \"<value>\" } }`; `-` reads stdin").option("--force", "Write values with placeholder problems").option("--dry-run", "Print the plan instead of writing").action(run("apply", apply));
|
|
657
|
+
cli.command("rename <from> <to>", "Rename a key (or every key under a parent) in all locales and usages").option("--no-usages", "Keep code unchanged").option("--dry-run", "Print the plan instead of writing").action(run("rename", rename));
|
|
658
|
+
cli.command("delete <key>", "Delete a key (or every key under a parent) in all locales").option("--locale <locale>", "Only in these locales (repeatable)").option("--dry-run", "Print the plan instead of writing").action(run("delete", remove));
|
|
659
|
+
cli.command("fill", "Add missing keys with empty values").option("--locale <locale>", "Only these locales (repeatable)").option("--copy-source", "Use the source value instead of an empty string").option("--dry-run", "Print the plan instead of writing").action(run("fill", fill));
|
|
660
|
+
cli.command("format", "Re-write resources with the configured sort and indent").option("--dry-run", "Print the plan instead of writing").action(run("format", format));
|
|
661
|
+
cli.command("extract [...files]", "Find hard-coded strings and turn them into keys").option("--list", "Print candidates and proposed keys").option("--plan <file>", "Write the extraction plan to a file to edit").option("--apply <file>", "Apply an (edited) extraction plan").option("--dry-run", "Print the plan instead of writing").action(run("extract", extract));
|
|
662
|
+
cli.command("prompt <kind>", "Print a prompt for an agent or LLM: `prompt translate --to <locale>` or `prompt review --locale <locale>`").option("--to <locale>", "Target locale (translate)").option("--locale <locale>", "Locale to review").option("--keys <glob>", "Only keys matching a glob").option("--namespace <ns>", "Only keys of a namespace").option("--limit <n>", "Messages per prompt (default 50)").option("--cursor <cursor>", "Continue from `nextCursor`").option("--format <format>", "markdown (default) or json").option("--no-context", "Leave out code around usages").action(run("prompt", prompt));
|
|
663
|
+
cli.command("ui", "Start the UI: browse and edit messages in the browser, with HTTP MCP at /__mcp").option("--port <port>", "Port (default: a free one from 9999)").option("--host <host>", "Bind host (default: localhost)").option("--no-open", "Do not open the browser").option("--no-auth", "Skip authentication (CI and e2e only)").action(run("ui", async (options) => (await uiCommands()).ui(options)));
|
|
664
|
+
cli.command("build", "Write a static, read-only report of the UI").option("--out-dir <dir>", "Output directory (default: .x18n/report)").action(run("build", async (options) => (await uiCommands()).build(options)));
|
|
665
|
+
cli.command("mcp", "Serve the MCP tools over stdio").action(run("mcp", async (options) => (await uiCommands()).mcp(options)));
|
|
666
|
+
cli.command("init", "Detect the setup and write x18n.config.ts").option("--format <format>", "ts (default), yml or json").option("--force", "Replace an existing config").action(run("init", init));
|
|
667
|
+
cli.command("migrate <source>", "Convert i18n-ally settings: `migrate i18n-ally`").option("--format <format>", "ts (default), yml or json").option("--dry-run", "Print the files instead of writing").option("--force", "Replace an existing config").action(run("migrate", migrate));
|
|
668
|
+
cli.command("schema [name]", "Print a JSON Schema: config (default) or plugin").action(run("schema", schema));
|
|
669
|
+
cli.command("plugin <action> <file>", "Plugin tools: `plugin eject <file.yml>` prints the TS equivalent").action(run("plugin eject", async (action, file, options) => {
|
|
670
|
+
if (action !== "eject") throw new Error(`unknown plugin action "${action}"`);
|
|
671
|
+
await eject(file, options);
|
|
672
|
+
}));
|
|
673
|
+
cli.help();
|
|
674
|
+
cli.version(version);
|
|
675
|
+
return cli;
|
|
676
|
+
}
|
|
677
|
+
process.stdout.on("error", (error) => {
|
|
678
|
+
if (error.code === "EPIPE") process.exit(0);
|
|
679
|
+
throw error;
|
|
680
|
+
});
|
|
681
|
+
const argv = process.argv.map((arg) => arg === "-" ? stdinArg : arg);
|
|
682
|
+
try {
|
|
683
|
+
createCli().parse(argv);
|
|
684
|
+
} catch (error) {
|
|
685
|
+
process.stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
686
|
+
process.exitCode = 2;
|
|
687
|
+
}
|
|
688
|
+
//#endregion
|
|
689
|
+
export { createCli };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { X18nError, applyTextEdits, envelope, isX18nError, toWireDiagnostic } from "@x18n/core";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { Buffer } from "node:buffer";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { join, relative } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline/promises";
|
|
7
|
+
import { loadWorkspace, stderrLogger } from "@x18n/node";
|
|
8
|
+
//#region src/context.ts
|
|
9
|
+
const cwd = () => process.cwd();
|
|
10
|
+
function useColor(options) {
|
|
11
|
+
if (options.json || process.env.NO_COLOR) return false;
|
|
12
|
+
if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== "0") return true;
|
|
13
|
+
return process.stdout.isTTY === true;
|
|
14
|
+
}
|
|
15
|
+
async function openWorkspace(options) {
|
|
16
|
+
return loadWorkspace({
|
|
17
|
+
cwd: options.root ?? cwd(),
|
|
18
|
+
configFile: options.config,
|
|
19
|
+
upward: options.root === void 0,
|
|
20
|
+
project: options.project,
|
|
21
|
+
cache: options.cache !== false,
|
|
22
|
+
logger: stderrLogger
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** Write commands work on one project; a monorepo needs `--project`. */
|
|
26
|
+
function singleProject(workspace) {
|
|
27
|
+
if (workspace.projects.length !== 1) throw new X18nError("X18N0003", `pick one with --project (${workspace.projects.map((p) => p.name).join(", ")})`);
|
|
28
|
+
return workspace.projects[0];
|
|
29
|
+
}
|
|
30
|
+
function displayPath(root, path) {
|
|
31
|
+
return relative(cwd(), join(root, path)).replace(/\\/g, "/") || ".";
|
|
32
|
+
}
|
|
33
|
+
function out(text) {
|
|
34
|
+
process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
35
|
+
}
|
|
36
|
+
function printJson(command, data, diagnostics = [], errors = []) {
|
|
37
|
+
const value = envelope(command, data, diagnostics, errors);
|
|
38
|
+
out(JSON.stringify(value, null, 2));
|
|
39
|
+
}
|
|
40
|
+
function wireDiagnostics(loaded, diagnostics) {
|
|
41
|
+
return diagnostics.map((d) => toWireDiagnostic(loaded.name, d, (path) => loaded.project.text(path)));
|
|
42
|
+
}
|
|
43
|
+
/** Exit code for an error: 2 usage or config, 3 decision needed, 4 stale plan, 1 otherwise. */
|
|
44
|
+
function exitCodeOf(error) {
|
|
45
|
+
if (!isX18nError(error)) return 2;
|
|
46
|
+
if (error.code === "X18N4003") return 3;
|
|
47
|
+
if (error.code === "X18N4004") return 4;
|
|
48
|
+
return /^X18N[01]/.test(error.code) ? 2 : 1;
|
|
49
|
+
}
|
|
50
|
+
function errorInfo(error) {
|
|
51
|
+
if (isX18nError(error)) return error.toJSON();
|
|
52
|
+
return {
|
|
53
|
+
code: "X18N0002",
|
|
54
|
+
message: error instanceof Error ? error.message : String(error),
|
|
55
|
+
hint: "",
|
|
56
|
+
docs: ""
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** Stands for a lone `-` argument (stdin). */
|
|
60
|
+
const stdinArg = "\0stdin";
|
|
61
|
+
async function readInput(source) {
|
|
62
|
+
if (source !== "-" && source !== "\0stdin") return readFile(source, "utf8");
|
|
63
|
+
const chunks = [];
|
|
64
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
65
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
66
|
+
}
|
|
67
|
+
/** Answers for the plan's decisions: defaults with `--yes`, a prompt in a TTY, else an error. */
|
|
68
|
+
async function answer(plan, options) {
|
|
69
|
+
const answers = {};
|
|
70
|
+
if (plan.decisions.length === 0) return answers;
|
|
71
|
+
if (options.yes) {
|
|
72
|
+
for (const decision of plan.decisions) answers[decision.id] = decision.default;
|
|
73
|
+
return answers;
|
|
74
|
+
}
|
|
75
|
+
if (options.json || !process.stdin.isTTY) throw new X18nError("X18N4003", plan.decisions.map((d) => `${d.message} (${d.options.map((o) => o.id).join(" | ")})`).join(" "), plan.decisions.map((d) => d.id));
|
|
76
|
+
const rl = createInterface({
|
|
77
|
+
input: process.stdin,
|
|
78
|
+
output: process.stderr
|
|
79
|
+
});
|
|
80
|
+
try {
|
|
81
|
+
for (const decision of plan.decisions) {
|
|
82
|
+
process.stderr.write(`${decision.message}\n${decision.options.map((o, i) => ` ${i + 1}) ${o.label}`).join("\n")}\n`);
|
|
83
|
+
const reply = await rl.question(`Choose [1]: `);
|
|
84
|
+
const option = decision.options[Number(reply || "1") - 1] ?? decision.options[0];
|
|
85
|
+
answers[decision.id] = option.id;
|
|
86
|
+
}
|
|
87
|
+
} finally {
|
|
88
|
+
rl.close();
|
|
89
|
+
}
|
|
90
|
+
return answers;
|
|
91
|
+
}
|
|
92
|
+
/** Changes as a small line diff, for `--dry-run` and the summary after a write. */
|
|
93
|
+
function formatPlan(project, root, plan) {
|
|
94
|
+
const lines = [];
|
|
95
|
+
for (const change of plan.changes) {
|
|
96
|
+
const path = displayPath(root, change.path);
|
|
97
|
+
if (change.type === "create") {
|
|
98
|
+
lines.push(`create ${path}`, ...change.content.split("\n").filter(Boolean).map((line) => `+ ${line}`));
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (change.type === "delete") {
|
|
102
|
+
lines.push(`delete ${path}`);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const before = project.text(change.path) ?? "";
|
|
106
|
+
const after = applyTextEdits(before, change.edits);
|
|
107
|
+
const a = before.split("\n");
|
|
108
|
+
const b = after.split("\n");
|
|
109
|
+
let start = 0;
|
|
110
|
+
while (start < a.length && start < b.length && a[start] === b[start]) start++;
|
|
111
|
+
let endA = a.length;
|
|
112
|
+
let endB = b.length;
|
|
113
|
+
while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
|
|
114
|
+
endA--;
|
|
115
|
+
endB--;
|
|
116
|
+
}
|
|
117
|
+
lines.push(`edit ${path}`, ...a.slice(start, endA).map((line) => `- ${line}`), ...b.slice(start, endB).map((line) => `+ ${line}`));
|
|
118
|
+
}
|
|
119
|
+
for (const warning of plan.warnings) lines.push(`warning: ${warning}`);
|
|
120
|
+
return lines.length ? lines.join("\n") : "No changes.";
|
|
121
|
+
}
|
|
122
|
+
function planData(root, plan, applied) {
|
|
123
|
+
return {
|
|
124
|
+
applied,
|
|
125
|
+
keys: plan.keys,
|
|
126
|
+
warnings: plan.warnings,
|
|
127
|
+
decisions: plan.decisions,
|
|
128
|
+
changes: plan.changes.map((change) => ({
|
|
129
|
+
...change,
|
|
130
|
+
file: displayPath(root, change.path)
|
|
131
|
+
}))
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
/** Plans, asks, then applies (or prints with `--dry-run`). */
|
|
135
|
+
async function runPlan(command, loaded, plan, options) {
|
|
136
|
+
if (options.dryRun) {
|
|
137
|
+
if (options.json) printJson(command, planData(loaded.root, plan, false));
|
|
138
|
+
else out(formatPlan(loaded.project, loaded.root, plan));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
const answers = await answer(plan, options);
|
|
142
|
+
const preview = formatPlan(loaded.project, loaded.root, plan);
|
|
143
|
+
await loaded.project.apply(plan, { answers });
|
|
144
|
+
if (options.json) printJson(command, planData(loaded.root, plan, true));
|
|
145
|
+
else out(preview);
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
export { openWorkspace as a, readInput as c, stdinArg as d, useColor as f, exitCodeOf as i, runPlan as l, displayPath as n, out as o, wireDiagnostics as p, errorInfo as r, printJson as s, cwd as t, singleProject as u };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { Check, Format, LocaleFinder, Plugin, Preset, Reporter, Scanner, UserConfig, defineConfig, definePlugin, definePreset } from "@x18n/core";
|
|
2
|
+
export { type Check, type Format, type LocaleFinder, type Plugin, type Preset, type Reporter, type Scanner, type UserConfig, defineConfig, definePlugin, definePreset };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineConfig, definePlugin, definePreset } from "@x18n/core";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@x18n/builtins/presets";
|
package/dist/presets.mjs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { a as openWorkspace, o as out, s as printJson, t as cwd } from "./context-Za_ea1Nk.mjs";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { createX18nDevframe } from "@x18n/ui";
|
|
5
|
+
import { createBuild } from "devframe/adapters/build";
|
|
6
|
+
import { createDevServer } from "devframe/adapters/dev";
|
|
7
|
+
import { createMcpServer } from "devframe/adapters/mcp";
|
|
8
|
+
import { buildOtpAuthUrl, getTempAuthCodeInfo } from "devframe/node/auth";
|
|
9
|
+
import { randomToken } from "devframe/utils/crypto-token";
|
|
10
|
+
import { launchEditor } from "devframe/utils/launch-editor";
|
|
11
|
+
//#region src/commands/ui.ts
|
|
12
|
+
/** Starts the UI dev server and keeps running until interrupted. */
|
|
13
|
+
async function ui(options) {
|
|
14
|
+
const workspace = await openWorkspace(options);
|
|
15
|
+
workspace.projects.forEach((p) => p.project.watch());
|
|
16
|
+
const editor = process.env.LAUNCH_EDITOR || process.env.VISUAL || process.env.EDITOR;
|
|
17
|
+
const definition = createX18nDevframe(workspace.projects, { openInEditor: editor ? async ({ project, path, line, column }) => launchEditor(`${join(project.root, path)}:${line}:${column}`, editor) : void 0 });
|
|
18
|
+
const mcpToken = randomToken();
|
|
19
|
+
const auth = options.auth !== false;
|
|
20
|
+
if (!auth) process.stderr.write("warning: --no-auth lets anything that reaches the port edit your files. Use it only in CI and e2e tests.\n");
|
|
21
|
+
const server = await createDevServer(definition, {
|
|
22
|
+
host: options.host ?? "localhost",
|
|
23
|
+
...options.port === void 0 ? {} : { port: Number(options.port) },
|
|
24
|
+
auth,
|
|
25
|
+
openBrowser: options.open !== false,
|
|
26
|
+
mcp: { authorization: mcpToken }
|
|
27
|
+
});
|
|
28
|
+
const url = `${server.origin}/`;
|
|
29
|
+
const code = auth ? getTempAuthCodeInfo().code : void 0;
|
|
30
|
+
const mcp = {
|
|
31
|
+
url: `${url}__mcp`,
|
|
32
|
+
token: mcpToken
|
|
33
|
+
};
|
|
34
|
+
if (options.json) printJson("ui", {
|
|
35
|
+
url,
|
|
36
|
+
code,
|
|
37
|
+
link: code && buildOtpAuthUrl(url, code),
|
|
38
|
+
mcp
|
|
39
|
+
});
|
|
40
|
+
else {
|
|
41
|
+
out(`x18n UI at ${url}`);
|
|
42
|
+
if (code) out(` auth code ${code}\n or open ${buildOtpAuthUrl(url, code)}`);
|
|
43
|
+
out(` MCP ${mcp.url}\n MCP token Authorization: Bearer ${mcp.token}`);
|
|
44
|
+
}
|
|
45
|
+
const stop = () => {
|
|
46
|
+
server.close().finally(() => process.exit(0));
|
|
47
|
+
};
|
|
48
|
+
process.once("SIGINT", stop);
|
|
49
|
+
process.once("SIGTERM", stop);
|
|
50
|
+
}
|
|
51
|
+
async function build(options) {
|
|
52
|
+
const workspace = await openWorkspace(options);
|
|
53
|
+
const outDir = resolve(cwd(), options.outDir ?? ".x18n/report");
|
|
54
|
+
const log = console.log;
|
|
55
|
+
console.log = console.error;
|
|
56
|
+
try {
|
|
57
|
+
await createBuild(createX18nDevframe(workspace.projects), { outDir });
|
|
58
|
+
} finally {
|
|
59
|
+
console.log = log;
|
|
60
|
+
}
|
|
61
|
+
if (options.json) printJson("build", { outDir });
|
|
62
|
+
else out(`Wrote the report to ${outDir}`);
|
|
63
|
+
}
|
|
64
|
+
/** MCP over stdio: stdout is the transport, so nothing else may print there. */
|
|
65
|
+
async function mcp(options) {
|
|
66
|
+
const workspace = await openWorkspace(options);
|
|
67
|
+
workspace.projects.forEach((p) => p.project.watch());
|
|
68
|
+
await createMcpServer(createX18nDevframe(workspace.projects), {
|
|
69
|
+
transport: "stdio",
|
|
70
|
+
serverName: "x18n"
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
//#endregion
|
|
74
|
+
export { build, mcp, ui };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@x18n/cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.3",
|
|
5
5
|
"description": "Manage and view i18n files of any project, for humans and agents",
|
|
6
6
|
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -38,10 +38,10 @@
|
|
|
38
38
|
"node": ">=22"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@x18n/builtins": "0.0.
|
|
42
|
-
"@x18n/core": "0.0.
|
|
43
|
-
"@x18n/node": "0.0.
|
|
44
|
-
"@x18n/ui": "0.0.
|
|
41
|
+
"@x18n/builtins": "0.0.3",
|
|
42
|
+
"@x18n/core": "0.0.3",
|
|
43
|
+
"@x18n/node": "0.0.3",
|
|
44
|
+
"@x18n/ui": "0.0.3",
|
|
45
45
|
"cac": "^7.1.0",
|
|
46
46
|
"devframe": "^1.2.5",
|
|
47
47
|
"yaml": "^2.9.1"
|