@localness/cli 0.0.0-stage → 0.1.1

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.mjs ADDED
@@ -0,0 +1,1440 @@
1
+ #!/usr/bin/env node
2
+ import { createInterface } from "node:readline/promises";
3
+ import { parseArgs } from "node:util";
4
+ import { LocalnessError, createClient, findRelease } from "@localness/sdk";
5
+ import { CONFIG_FILE_NAME, DIFF_KINDS, FORCED_PULL_KINDS, FORCED_PUSH_KINDS, PULL_KINDS, PUSH_KINDS, SYNC_PULL_KINDS, applyPush, checkPlan, compareLocaleFiles, deletePlan, describeBlocked, describeViolations, findConfigFile, listPlans, loadConfig, loadPlan, matchLocalEntries, parseConfig, planPush, prunePlans, pullLocaleFiles, readBase, readLocalFiles, recordPush, resolveRelease, savePlan, writeBase, writeConfigFields } from "@localness/sdk/sync";
6
+ import { dirname, join, relative, resolve } from "node:path";
7
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
8
+ import { DEFAULT_LOCALE_FILE_PATTERN, LOCALE_PLACEHOLDER, LocaleFileFormat, localeFileName, localeFilesScopeError, readLocaleFile } from "@localness/contract/locale-file";
9
+ import { spawn } from "node:child_process";
10
+ import { createHash, randomBytes } from "node:crypto";
11
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
12
+ import { claimReview, createReviewSession, hasEditor, isAlive, parseReviewInput, prepareReviewDir, readJson, reviewPage, reviewPaths, takenNames, writeJson } from "@localness/sdk/review";
13
+ import { createServer } from "node:http";
14
+ import { fileURLToPath } from "node:url";
15
+ // package.json
16
+ var version = "0.1.1";
17
+ // src/env.ts
18
+ const TOKEN_ENV = "LOCALNESS_TOKEN";
19
+ const ENV_FILE = ".env.local";
20
+ /** `KEY=value` lines of a dotenv file; `#` comments, `export` and quotes allowed. */
21
+ function parseEnvFile(source) {
22
+ const values = {};
23
+ for (const line of source.split(/\r?\n/)) {
24
+ const match = /^\s*(?:export\s+)?([\w.-]+)\s*=\s*(.*)$/.exec(line);
25
+ if (!match) continue;
26
+ let value = match[2].trim();
27
+ const quote = value[0];
28
+ if ((quote === "\"" || quote === "'") && value.endsWith(quote)) value = value.slice(1, -1);
29
+ else value = value.replace(/\s+#.*$/, "");
30
+ values[match[1]] = value;
31
+ }
32
+ return values;
33
+ }
34
+ /**
35
+ * `LOCALNESS_TOKEN` from `dir/.env.local`, else from `env`; undefined when
36
+ * neither has one. `dir` is the folder of `localness.config.json`.
37
+ */
38
+ async function findEnvToken(dir, env) {
39
+ const source = await readFile(join(dir, ENV_FILE), "utf8").catch((error) => {
40
+ if (error.code === "ENOENT") return void 0;
41
+ throw error;
42
+ });
43
+ return source && parseEnvFile(source)["LOCALNESS_TOKEN"]?.trim() || env["LOCALNESS_TOKEN"]?.trim() || void 0;
44
+ }
45
+ // src/shared.ts
46
+ const OPTIONS = {
47
+ config: { type: "string" },
48
+ keys: { type: "string" },
49
+ locales: { type: "string" },
50
+ prune: { type: "boolean" },
51
+ "dry-run": { type: "boolean" },
52
+ json: { type: "boolean" },
53
+ "base-url": { type: "string" },
54
+ project: { type: "string" },
55
+ dir: { type: "string" },
56
+ pattern: { type: "string" },
57
+ format: { type: "string" },
58
+ force: { type: "boolean" },
59
+ agent: { type: "string" },
60
+ "agents-md": { type: "boolean" },
61
+ root: { type: "string" },
62
+ release: { type: "string" },
63
+ none: { type: "boolean" },
64
+ use: { type: "boolean" },
65
+ match: { type: "string" },
66
+ timeout: { type: "string" },
67
+ open: { type: "string" },
68
+ yes: {
69
+ type: "boolean",
70
+ short: "y"
71
+ },
72
+ help: {
73
+ type: "boolean",
74
+ short: "h"
75
+ },
76
+ version: {
77
+ type: "boolean",
78
+ short: "v"
79
+ }
80
+ };
81
+ function list(value) {
82
+ if (value === void 0) return void 0;
83
+ const items = value.split(",").map((item) => item.trim()).filter(Boolean);
84
+ return items.length > 0 ? items : void 0;
85
+ }
86
+ function plural(count, noun) {
87
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
88
+ }
89
+ async function readToken(io, dir) {
90
+ const token = await findEnvToken(dir, io.env);
91
+ if (!token) throw new Error(`Set ${TOKEN_ENV} to a Localness API token in ${join(dir, ENV_FILE)} or the environment.`);
92
+ return token;
93
+ }
94
+ const AGENT_ENV = "LOCALNESS_AGENT";
95
+ /** Variables coding agents set in the shells they run; their value is not checked. */
96
+ const AGENT_MARKERS = [
97
+ "AI_AGENT",
98
+ "CLAUDECODE",
99
+ "CURSOR_AGENT",
100
+ "COPILOT_CLI",
101
+ "CODEX_SANDBOX",
102
+ "GEMINI_CLI"
103
+ ];
104
+ /**
105
+ * `cli/<version>`, plus `; agent` when an agent runs it, so the project's
106
+ * history can tell. `LOCALNESS_AGENT=1` or `0` overrides the detection.
107
+ */
108
+ function clientOf(env) {
109
+ const flag = env[AGENT_ENV];
110
+ return `cli/${version}${(flag !== void 0 && flag !== "" ? flag !== "0" : AGENT_MARKERS.some((name) => env[name])) ? "; agent" : ""}`;
111
+ }
112
+ async function loadProject(io, values) {
113
+ const path = values.config ?? await findConfigFile(io.cwd);
114
+ if (!path) throw new Error("No localness.config.json here or above; run \"localness init\" first.");
115
+ const loaded = await loadConfig(path);
116
+ return {
117
+ loaded,
118
+ client: createClient({
119
+ baseUrl: loaded.config.baseUrl,
120
+ token: await readToken(io, loaded.root),
121
+ project: loaded.config.project,
122
+ client: clientOf(io.env),
123
+ fetch: io.fetch
124
+ })
125
+ };
126
+ }
127
+ // src/apply.ts
128
+ async function runApply(io, values, id) {
129
+ const { client, loaded } = await loadProject(io, values);
130
+ if (!id) {
131
+ await prunePlans(loaded);
132
+ const plans = await listPlans(loaded);
133
+ if (values.json) io.stdout(`${JSON.stringify(plans.map((plan) => ({
134
+ id: plan.id,
135
+ createdAt: plan.createdAt,
136
+ expiresAt: plan.expiresAt,
137
+ keys: plan.keys.length
138
+ })), null, 2)}\n`);
139
+ else if (plans.length === 0) io.stdout("No plans; \"localness push\" makes one.\n");
140
+ else {
141
+ for (const plan of plans) io.stdout(`${plan.id} ${plural(plan.keys.length, "key")}, expires ${plan.expiresAt}\n`);
142
+ io.stdout("Run \"localness apply <id>\" to write one.\n");
143
+ }
144
+ return 2;
145
+ }
146
+ const plan = await loadPlan(loaded, id);
147
+ const check = await checkPlan(client, plan);
148
+ if (check.expired || check.stale.length > 0) {
149
+ await deletePlan(loaded, id);
150
+ throw new Error(check.expired ? `Plan ${id} expired; run "localness push" again.` : `The project changed since plan ${id} was made (${check.stale.join(", ")}); nothing was written. Run "localness push" again.`);
151
+ }
152
+ const result = await applyPush(client, plan, check);
153
+ await deletePlan(loaded, id);
154
+ await writeBase(loaded, recordPush(await readBase(loaded), plan, result));
155
+ if (values.json) io.stdout(`${JSON.stringify({
156
+ id,
157
+ ...result
158
+ }, null, 2)}\n`);
159
+ else {
160
+ for (const done of result.written) {
161
+ const parts = [done.created && `created, ${plan.sourceLocale} published`, done.locales.length > 0 && `drafts for ${done.locales.join(", ")}`].filter(Boolean);
162
+ io.stdout(` ${done.key}: ${parts.join("; ")}\n`);
163
+ }
164
+ io.stdout(`Wrote ${plural(result.written.length, "key")} of ${plan.keys.length}.\n`);
165
+ if (result.failed) io.stdout(`Stopped at ${result.failed.key}: ${result.failed.message}${result.failed.conflict ? " Someone changed it meanwhile; run \"localness diff\"." : ""}\n`);
166
+ else if (result.written.some((done) => done.locales.length > 0)) io.stdout("Drafts reach the bundle once published in the web app.\n");
167
+ }
168
+ return result.failed ? 2 : 0;
169
+ }
170
+ // src/diff.ts
171
+ const MAX_TEXT = 60;
172
+ function quote(text) {
173
+ if (text === null) return "(none)";
174
+ const short = text.length > MAX_TEXT ? `${text.slice(0, 59)}…` : text;
175
+ return JSON.stringify(short);
176
+ }
177
+ function detail(entry) {
178
+ const { local, platform, draft, base } = entry;
179
+ switch (entry.kind) {
180
+ case "platform-added": return quote(platform);
181
+ case "platform-changed": return `${quote(local)} → ${quote(platform)}`;
182
+ case "platform-deleted": return `${quote(local)} (deleted in the project)`;
183
+ case "local-added": return `${quote(local)} (${entry.onPlatform ? "no text" : "not"} in the project)`;
184
+ case "local-changed": return `${quote(platform)} → ${quote(local)}`;
185
+ case "local-deleted": return `${quote(platform)} (deleted locally)`;
186
+ case "different": return `local ${quote(local)}, project ${quote(platform)}`;
187
+ case "conflict": return [
188
+ `local ${quote(local)}`,
189
+ `project ${quote(platform)}`,
190
+ draft !== null && draft !== platform && `unpublished ${quote(draft)}`,
191
+ `base ${quote(base)}`
192
+ ].filter(Boolean).join(", ");
193
+ case "pending-publish": return `${quote(local)} (draft waiting for a publish)`;
194
+ }
195
+ }
196
+ const KIND_WIDTH = Math.max(...DIFF_KINDS.map((kind) => kind.length));
197
+ function describeEntry(entry) {
198
+ return ` ${entry.kind.padEnd(KIND_WIDTH)} ${entry.key}: ${detail(entry)}`;
199
+ }
200
+ function countKinds(entries) {
201
+ const counts = /* @__PURE__ */ new Map();
202
+ for (const entry of entries) counts.set(entry.kind, (counts.get(entry.kind) ?? 0) + 1);
203
+ return DIFF_KINDS.filter((kind) => counts.has(kind)).map((kind) => `${counts.get(kind)} ${kind}`).join(", ");
204
+ }
205
+ function filesByLocale(comparison) {
206
+ return Object.fromEntries(comparison.files.map((file) => [file.locale, file.relativePath]));
207
+ }
208
+ const HINTS = [
209
+ [[
210
+ "platform-added",
211
+ "platform-changed",
212
+ "different"
213
+ ], "\"localness pull\" takes the project's text for platform-added, platform-changed and different."],
214
+ [["local-added", "local-changed"], "\"localness push\" plans sending local-added and local-changed."],
215
+ [[
216
+ "conflict",
217
+ "local-deleted",
218
+ "platform-deleted"
219
+ ], "Name a key to choose a side: \"pull --keys <key>\" or \"push --keys <key>\"; \"pull --prune\" drops platform-deleted."]
220
+ ];
221
+ async function runDiff(io, values) {
222
+ const { client, loaded } = await loadProject(io, values);
223
+ const comparison = await compareLocaleFiles(loaded, client, {
224
+ locales: list(values.locales),
225
+ keys: list(values.keys)
226
+ });
227
+ const files = filesByLocale(comparison);
228
+ const { entries } = comparison;
229
+ if (values.json) io.stdout(`${JSON.stringify({
230
+ sourceLocale: comparison.sourceLocale,
231
+ locales: comparison.locales,
232
+ content: comparison.content,
233
+ hasBase: comparison.base !== null,
234
+ files,
235
+ differences: entries
236
+ }, null, 2)}\n`);
237
+ else if (entries.length === 0) io.stdout(`Up to date: ${comparison.locales.length} locale files match the project's ${comparison.content} text.\n`);
238
+ else {
239
+ for (const locale of comparison.locales) {
240
+ const own = entries.filter((entry) => entry.locale === locale);
241
+ if (own.length === 0) continue;
242
+ io.stdout(`${files[locale]} (${locale})\n`);
243
+ for (const entry of own) io.stdout(`${describeEntry(entry)}\n`);
244
+ }
245
+ io.stdout(`\n${entries.length} differences against the project's ${comparison.content} text: ${countKinds(entries)}.\n`);
246
+ if (comparison.base === null) io.stdout("No base yet, so changed text shows as \"different\"; pull or sync records one.\n");
247
+ for (const [kinds, hint] of HINTS) if (entries.some((entry) => kinds.includes(entry.kind))) io.stdout(`${hint}\n`);
248
+ }
249
+ return entries.length > 0 ? 1 : 0;
250
+ }
251
+ // src/init.ts
252
+ const SKIP_DIRS = /* @__PURE__ */ new Set([
253
+ "node_modules",
254
+ "dist",
255
+ "build",
256
+ "out",
257
+ "coverage",
258
+ "vendor"
259
+ ]);
260
+ const MAX_DEPTH = 6;
261
+ const LOCALE_NAME = /^([a-z]{2,3})(?:[-_][a-z0-9]{2,8})*$/i;
262
+ const languageNames = new Intl.DisplayNames(["en"], {
263
+ type: "language",
264
+ fallback: "none"
265
+ });
266
+ /** `en`, `zh-CN`, `pt_br`: a known language, optionally with subtags. */
267
+ function isLocaleName(name) {
268
+ const language = LOCALE_NAME.exec(name)?.[1];
269
+ return language !== void 0 && languageNames.of(language.toLowerCase()) !== void 0;
270
+ }
271
+ /** Relative `/`-separated paths of the JSON files under `root`. */
272
+ async function scan(root, dir = root, depth = 0) {
273
+ const found = [];
274
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
275
+ const path = join(dir, entry.name);
276
+ if (entry.isDirectory()) {
277
+ if (depth < MAX_DEPTH && !entry.name.startsWith(".") && !SKIP_DIRS.has(entry.name)) found.push(...await scan(root, path, depth + 1));
278
+ } else if (entry.isFile() && entry.name.toLowerCase().endsWith(".json")) found.push(relative(root, path).split("\\").join("/"));
279
+ }
280
+ return found;
281
+ }
282
+ /**
283
+ * Candidate layouts — `dir/{locale}.json` or `dir/{locale}/name.json` — with
284
+ * the most locales first.
285
+ */
286
+ function groupLocaleFiles(paths) {
287
+ const groups = /* @__PURE__ */ new Map();
288
+ const add = (dir, pattern, name, path) => {
289
+ if (localeFilesScopeError(dir, pattern) !== null) return;
290
+ const id = `${dir}\n${pattern}`;
291
+ const group = groups.get(id) ?? {
292
+ dir,
293
+ pattern,
294
+ files: /* @__PURE__ */ new Map()
295
+ };
296
+ group.files.set(name, path);
297
+ groups.set(id, group);
298
+ };
299
+ for (const path of paths) {
300
+ const segments = path.split("/");
301
+ const file = segments.at(-1);
302
+ const name = file.slice(0, -5);
303
+ if (isLocaleName(name)) add(segments.slice(0, -1).join("/"), DEFAULT_LOCALE_FILE_PATTERN, name, path);
304
+ const parent = segments.at(-2);
305
+ if (segments.length >= 3 && parent && isLocaleName(parent)) add(segments.slice(0, -2).join("/"), `${LOCALE_PLACEHOLDER}/${file}`, parent, path);
306
+ }
307
+ return [...groups.values()].sort((a, b) => b.files.size - a.files.size || a.dir.length - b.dir.length);
308
+ }
309
+ /** Nested when any file nests; flat when keys contain dots but never nest. */
310
+ async function detectFormat(root, paths) {
311
+ let dotted = false;
312
+ for (const path of paths) {
313
+ let segmentsList;
314
+ try {
315
+ const source = await readFile(join(root, path), "utf8");
316
+ segmentsList = [...readLocaleFile(source).paths.values()];
317
+ } catch {
318
+ continue;
319
+ }
320
+ for (const segments of segmentsList) {
321
+ if (segments.length > 1) return LocaleFileFormat.NESTED_JSON;
322
+ if (segments[0].includes(".")) dotted = true;
323
+ }
324
+ }
325
+ return dotted ? LocaleFileFormat.FLAT_JSON : LocaleFileFormat.NESTED_JSON;
326
+ }
327
+ const loose = (name) => name.toLowerCase().replace(/_/g, "-");
328
+ /**
329
+ * Pairs project locales with file names: exactly as `localeFileName` names
330
+ * them, else ignoring case and `_`/`-`, which then needs a `localeMap` entry.
331
+ */
332
+ function matchLocales(locales, names) {
333
+ const localeMap = {};
334
+ const matched = /* @__PURE__ */ new Set();
335
+ const withoutFile = [];
336
+ for (const locale of locales) {
337
+ const expected = localeFileName(locale, null);
338
+ const name = names.find((candidate) => candidate === expected) ?? names.find((candidate) => loose(candidate) === loose(expected) || loose(candidate) === loose(locale));
339
+ if (!name) {
340
+ withoutFile.push(locale);
341
+ continue;
342
+ }
343
+ matched.add(name);
344
+ if (name !== expected) localeMap[locale] = name;
345
+ }
346
+ return {
347
+ localeMap,
348
+ withoutFile,
349
+ unmatched: names.filter((name) => !matched.has(name))
350
+ };
351
+ }
352
+ function parseFormat(value) {
353
+ const formats = Object.values(LocaleFileFormat);
354
+ if (!formats.includes(value)) throw new Error(`--format must be ${formats.join(" or ")}.`);
355
+ return value;
356
+ }
357
+ async function runInit(io, values) {
358
+ const target = resolve(io.cwd, values.config ?? CONFIG_FILE_NAME);
359
+ const root = dirname(target);
360
+ const shown = relative(io.cwd, target) || CONFIG_FILE_NAME;
361
+ if (await stat(target).then(() => true, () => false) && !values.force) throw new Error(`${shown} already exists; pass --force to replace it.`);
362
+ const baseUrl = values["base-url"]?.trim();
363
+ if (!baseUrl) throw new Error("Pass --base-url <url> of the Localness instance.");
364
+ const notes = [];
365
+ const groups = groupLocaleFiles(await scan(root));
366
+ let group;
367
+ if (values.dir !== void 0) {
368
+ const dir = values.dir.replace(/\\/g, "/").replace(/\/+$/, "");
369
+ const pattern = values.pattern ?? DEFAULT_LOCALE_FILE_PATTERN;
370
+ group = groups.find((candidate) => candidate.dir === dir && candidate.pattern === pattern) ?? {
371
+ dir,
372
+ pattern,
373
+ files: /* @__PURE__ */ new Map()
374
+ };
375
+ if (group.files.size === 0) notes.push(`No files match ${dir}/${pattern} yet.`);
376
+ } else {
377
+ group = groups[0];
378
+ if (!group) throw new Error("Found no locale JSON files like src/locales/en.json; pass --dir and --pattern.");
379
+ const others = groups.slice(1, 4);
380
+ if (others.length > 0) notes.push(`Also found ${others.map((other) => `${other.dir}/${other.pattern}`).join(", ")}; pass --dir and --pattern to use another.`);
381
+ }
382
+ const format = values.format ? parseFormat(values.format) : await detectFormat(root, group.files.values());
383
+ const names = [...group.files.keys()].sort();
384
+ const config = { baseUrl };
385
+ if (values.project) config.project = values.project;
386
+ config.files = {
387
+ dir: group.dir,
388
+ pattern: group.pattern,
389
+ format
390
+ };
391
+ const token = await findEnvToken(root, io.env);
392
+ if (token) {
393
+ const meta = await createClient({
394
+ baseUrl,
395
+ token,
396
+ project: values.project,
397
+ fetch: io.fetch
398
+ }).meta();
399
+ config.project ??= meta.project.name;
400
+ if (values.release) {
401
+ const release = findRelease(meta.releases, values.release);
402
+ if (!release) throw new Error(`The project has no release "${values.release}"; it has ${meta.releases.map((item) => item.name).join(", ") || "none"}.`);
403
+ config.release = release.name;
404
+ } else if (meta.releases.length > 0) notes.push(`New keys get no release; "localness releases use" picks one (${meta.releases.map((item) => item.name).join(", ")}).`);
405
+ const { localeMap, withoutFile, unmatched } = matchLocales(meta.locales, names);
406
+ if (Object.keys(localeMap).length > 0) config.localeMap = localeMap;
407
+ if (unmatched.length > 0) notes.push(`No project locale for ${unmatched.join(", ")} (project: ${meta.locales.join(", ")}); map them in "localeMap", e.g. { "zh_cn": "zh" }.`);
408
+ if (withoutFile.length > 0 && names.length > 0) notes.push(`No file yet for ${withoutFile.join(", ")}; "localness pull" creates them, or list the locales to sync in "locales".`);
409
+ } else {
410
+ if (values.release) config.release = values.release;
411
+ notes.push(`${TOKEN_ENV} is not set in ${ENV_FILE} or the environment, so file names were not checked against the project's locales.`);
412
+ }
413
+ parseConfig(JSON.stringify(config), shown);
414
+ const text = `${JSON.stringify(config, null, 2)}\n`;
415
+ const dryRun = values["dry-run"] ?? false;
416
+ if (!dryRun) await writeFile(target, text, "utf8");
417
+ if (values.json) {
418
+ io.stdout(`${JSON.stringify({
419
+ path: shown,
420
+ dryRun,
421
+ config,
422
+ files: names,
423
+ notes
424
+ }, null, 2)}\n`);
425
+ return 0;
426
+ }
427
+ io.stdout(`${dryRun ? "Would write" : "Wrote"} ${shown}:\n${text}`);
428
+ if (names.length > 0) io.stdout(`Locale files: ${names.join(", ")}\n`);
429
+ for (const note of notes) io.stdout(`- ${note}\n`);
430
+ return 0;
431
+ }
432
+ // src/lookup.ts
433
+ const BATCH = 500;
434
+ /**
435
+ * Which existing keys hold each text. Keys only in the source-locale file (not
436
+ * pushed yet) count too, so extraction does not mint a second key for the
437
+ * same text.
438
+ */
439
+ async function lookupTexts(io, values, wanted) {
440
+ const { client, loaded } = await loadProject(io, values);
441
+ const platform = [];
442
+ for (let start = 0; start < wanted.length; start += BATCH) {
443
+ const page = await client.match(wanted.slice(start, start + BATCH));
444
+ platform.push(...page.matches);
445
+ }
446
+ const meta = await client.meta();
447
+ const [local] = loaded.config.files && meta.sourceLocale ? await readLocalFiles(loaded, [meta.sourceLocale]) : [];
448
+ const entries = local?.content.entries ?? {};
449
+ const localKeys = matchLocalEntries(entries, platform.map((match) => match.text));
450
+ return {
451
+ client,
452
+ loaded,
453
+ meta,
454
+ entries,
455
+ matches: platform.map(({ text, keys }, index) => {
456
+ const known = new Set(keys.map((hit) => hit.key));
457
+ const hits = keys.map((hit) => ({
458
+ ...hit,
459
+ source: "platform"
460
+ }));
461
+ for (const key of localKeys[index]) if (!known.has(key)) hits.push({
462
+ key,
463
+ sourceText: entries[key],
464
+ source: "local"
465
+ });
466
+ return {
467
+ text,
468
+ keys: hits
469
+ };
470
+ })
471
+ };
472
+ }
473
+ /**
474
+ * Prints {@link lookupTexts}; writes nothing. JSON output adds what naming a
475
+ * new key needs: the project's key convention and namespaces.
476
+ */
477
+ async function runMatch(io, values, texts) {
478
+ const wanted = texts.filter((text) => text.trim());
479
+ if (wanted.length === 0) throw new Error("Usage: localness match \"<text>\" [\"<text>\" ...]");
480
+ const { meta, matches } = await lookupTexts(io, values, wanted);
481
+ if (values.json) {
482
+ const result = {
483
+ matches,
484
+ convention: meta.keyConvention ?? null,
485
+ namespaces: (meta.namespaces ?? []).map((namespace) => namespace.name)
486
+ };
487
+ io.stdout(`${JSON.stringify(result, null, 2)}\n`);
488
+ return 0;
489
+ }
490
+ for (const { text, keys } of matches) {
491
+ const hits = keys.map((hit) => `${hit.key}${hit.source === "local" ? " (local)" : hit.draft ? " (draft)" : ""}`);
492
+ const found = hits.length === 0 ? "no key" : hits.length === 1 ? hits[0] : `${hits.length} keys, pick one: ${hits.join(", ")}`;
493
+ io.stdout(`${JSON.stringify(text)} -> ${found}\n`);
494
+ }
495
+ return 0;
496
+ }
497
+ // src/pull.ts
498
+ /** Writes the files and records the base, unless `dryRun`. */
499
+ async function pullInto(loaded, comparison, options) {
500
+ return {
501
+ files: await pullLocaleFiles(loaded, comparison, options),
502
+ kept: options.prune ? 0 : comparison.entries.filter((entry) => !entry.onPlatform && entry.local !== null).length
503
+ };
504
+ }
505
+ function describePull(io, run, dryRun) {
506
+ for (const file of run.files) {
507
+ const parts = [
508
+ file.set.length > 0 && `${file.set.length} set`,
509
+ file.removed.length > 0 && `${file.removed.length} removed`,
510
+ file.skipped.length > 0 && `${file.skipped.length} skipped`
511
+ ].filter(Boolean);
512
+ io.stdout(`${file.relativePath}${file.created ? " (new)" : ""}: ${parts.join(", ")}\n`);
513
+ for (const key of file.skipped) io.stdout(` skipped ${key}: its path collides with another key in the file\n`);
514
+ }
515
+ const written = run.files.filter((file) => file.output !== null).length;
516
+ io.stdout(written === 0 ? "Nothing to write.\n" : `${dryRun ? "Dry run: would write" : "Wrote"} ${plural(written, "file")}.\n`);
517
+ if (run.kept > 0) io.stdout(`Kept ${plural(run.kept, "local key")} the project does not have; --prune removes them.\n`);
518
+ }
519
+ function pullJson(run, dryRun) {
520
+ return {
521
+ dryRun,
522
+ files: run.files.map(({ output: _, path: __, ...file }) => file),
523
+ kept: run.kept
524
+ };
525
+ }
526
+ async function runPull(io, values) {
527
+ const { client, loaded } = await loadProject(io, values);
528
+ const keys = list(values.keys);
529
+ const comparison = await compareLocaleFiles(loaded, client, {
530
+ locales: list(values.locales),
531
+ keys
532
+ });
533
+ const kinds = keys ? FORCED_PULL_KINDS : PULL_KINDS;
534
+ const dryRun = values["dry-run"] ?? false;
535
+ const run = await pullInto(loaded, comparison, {
536
+ kinds,
537
+ prune: values.prune ?? false,
538
+ dryRun
539
+ });
540
+ const left = comparison.entries.filter((entry) => !kinds.includes(entry.kind) && entry.kind !== "pending-publish" && entry.onPlatform);
541
+ if (values.json) {
542
+ io.stdout(`${JSON.stringify({
543
+ ...pullJson(run, dryRun),
544
+ left: left.map(({ locale, key, kind }) => ({
545
+ locale,
546
+ key,
547
+ kind
548
+ }))
549
+ }, null, 2)}\n`);
550
+ return 0;
551
+ }
552
+ describePull(io, run, dryRun);
553
+ if (left.length > 0) io.stdout(`Left ${countKinds(left)}; "localness diff" shows them, "pull --keys <key>" takes the project's text.\n`);
554
+ return 0;
555
+ }
556
+ // src/push.ts
557
+ /** Never pushed without naming the key: either side may be the newer one. */
558
+ const NEEDS_KEYS = ["different", "conflict"];
559
+ async function planPushFrom(io, loaded, client, comparison, options) {
560
+ const plan = planPush(loaded, comparison, { kinds: options.kinds });
561
+ if (plan.keys.some((item) => item.create)) plan.release = await resolveRelease(loaded, client);
562
+ if (!options.dryRun) await prunePlans(loaded);
563
+ return {
564
+ plan,
565
+ path: plan.keys.length > 0 && !options.dryRun ? relative(io.cwd, await savePlan(loaded, plan)) : null,
566
+ leftOut: comparison.entries.filter((entry) => NEEDS_KEYS.includes(entry.kind) && !options.kinds.includes(entry.kind))
567
+ };
568
+ }
569
+ function pushJson({ plan, path, leftOut }) {
570
+ return {
571
+ id: path ? plan.id : null,
572
+ path,
573
+ expiresAt: path ? plan.expiresAt : null,
574
+ sourceLocale: plan.sourceLocale,
575
+ release: plan.release?.name ?? null,
576
+ keys: plan.keys,
577
+ blocked: plan.blocked,
578
+ warnings: plan.warnings,
579
+ leftOut: leftOut.map(({ locale, key, kind }) => ({
580
+ locale,
581
+ key,
582
+ kind
583
+ }))
584
+ };
585
+ }
586
+ function describePush(io, planned, dryRun) {
587
+ const { plan, path, leftOut } = planned;
588
+ if (plan.keys.length === 0) io.stdout("Nothing to push.\n");
589
+ else {
590
+ const created = plan.keys.filter((item) => item.create).length;
591
+ io.stdout(`${dryRun ? "Would plan" : `Plan ${plan.id}`}: ${plural(plan.keys.length, "key")}${created > 0 ? ` (${created} new${plan.release ? `, labelled ${plan.release.name}` : ""})` : ""}\n`);
592
+ for (const item of plan.keys) {
593
+ io.stdout(` ${item.create ? "create" : "update"} ${item.key}\n`);
594
+ if (item.create) io.stdout(` ${plan.sourceLocale}: ${quote(item.create.sourceText)} (published)\n`);
595
+ for (const [locale, write] of Object.entries(item.locales)) {
596
+ const from = write.draft ?? write.platform;
597
+ io.stdout(` ${locale}: ${from === null ? "" : `${quote(from)} → `}${quote(write.text)} (draft)\n`);
598
+ }
599
+ }
600
+ }
601
+ if (plan.blocked.length > 0) {
602
+ io.stdout("Blocked:\n");
603
+ for (const item of plan.blocked) io.stdout(` ${item.key} (${item.locale}): ${describeBlocked(item, plan.sourceLocale)}\n`);
604
+ }
605
+ if (plan.warnings.length > 0) {
606
+ io.stdout("Created, but off the suggested key style:\n");
607
+ for (const item of plan.warnings) io.stdout(` ${item.key}: ${describeViolations(item.violations)}\n`);
608
+ }
609
+ if (leftOut.length > 0) io.stdout(`Left out ${countKinds(leftOut)}; "push --keys <key>" sends the local text.\n`);
610
+ if (path) io.stdout(`Saved ${path}, valid for an hour. "localness apply ${plan.id}" writes it; drafts wait for a publish in the web app.\n`);
611
+ }
612
+ async function runPush(io, values) {
613
+ const { client, loaded } = await loadProject(io, values);
614
+ const keys = list(values.keys);
615
+ const comparison = await compareLocaleFiles(loaded, client, {
616
+ locales: list(values.locales),
617
+ keys
618
+ });
619
+ const dryRun = values["dry-run"] ?? false;
620
+ const planned = await planPushFrom(io, loaded, client, comparison, {
621
+ kinds: keys ? FORCED_PUSH_KINDS : PUSH_KINDS,
622
+ dryRun
623
+ });
624
+ if (values.json) io.stdout(`${JSON.stringify(pushJson(planned), null, 2)}\n`);
625
+ else describePush(io, planned, dryRun);
626
+ return 0;
627
+ }
628
+ // src/releases.ts
629
+ const USAGE$1 = `Usage:
630
+ localness releases List releases; * marks the config's
631
+ localness releases use [name] | --none Label new keys with a release, or none
632
+ localness releases create <name> [--use]
633
+ localness releases add <release> <key...> | --match <glob> [--yes]
634
+ localness releases remove <release> <key...> | --match <glob> [--yes]`;
635
+ /** `*` matches any run of characters, `?` one; the whole key must match. */
636
+ function globToRegExp(glob) {
637
+ const source = glob.split("").map((char) => char === "*" ? ".*" : char === "?" ? "." : char.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("");
638
+ return new RegExp(`^${source}$`);
639
+ }
640
+ async function releasesOf(client) {
641
+ const meta = await client.meta();
642
+ return {
643
+ releases: [...meta.releases].sort((a, b) => a.sort - b.sort),
644
+ sourceLocale: meta.sourceLocale
645
+ };
646
+ }
647
+ function requireRelease(releases, name) {
648
+ const found = findRelease(releases, name);
649
+ if (!found) throw new Error(`The project has no release "${name}"; it has ${releases.map((release) => release.name).join(", ") || "none"}.`);
650
+ return found;
651
+ }
652
+ async function choose(io, releases) {
653
+ if (!io.prompt) throw new Error("Pass a release name, or --none.\n" + USAGE$1);
654
+ releases.forEach((release, index) => io.stdout(` ${index + 1}. ${release.name}\n`));
655
+ io.stdout(" 0. None\n");
656
+ const answer = (await io.prompt("Release for new keys: ")).trim();
657
+ const index = Number(answer);
658
+ if (answer === "0") return null;
659
+ return (Number.isInteger(index) ? releases[index - 1] : void 0) ?? requireRelease(releases, answer);
660
+ }
661
+ async function use(io, loaded, release, json) {
662
+ await writeConfigFields(loaded.path, { release: release?.name });
663
+ if (json) io.stdout(`${JSON.stringify({ release: release?.name ?? null })}\n`);
664
+ else io.stdout(release ? `New keys will be labelled ${release.name}.\n` : "New keys will have no release.\n");
665
+ return 0;
666
+ }
667
+ async function label(io, values, client, mode, [name, ...keys]) {
668
+ if (!name || keys.length === 0 === (values.match === void 0)) throw new Error(`Name a release and either keys or --match.\n${USAGE$1}`);
669
+ const { releases, sourceLocale } = await releasesOf(client);
670
+ const release = requireRelease(releases, name);
671
+ const result = await client.keyStates({
672
+ locales: sourceLocale ? [sourceLocale] : void 0,
673
+ keys: keys.length > 0 ? keys : void 0
674
+ });
675
+ const found = new Map(result.keys.map((state) => [state.key, state]));
676
+ const missing = keys.filter((key) => !found.has(key));
677
+ if (missing.length > 0) throw new Error(`The project has no key ${missing.join(", ")}.`);
678
+ const pattern = values.match === void 0 ? null : globToRegExp(values.match);
679
+ const id = Number(release.id);
680
+ const targets = (pattern ? result.keys.filter((state) => pattern.test(state.key)) : keys.map((key) => found.get(key))).filter((state) => state.releaseIds.includes(id) === (mode === "remove"));
681
+ const verb = mode === "add" ? "Label" : "Unlabel";
682
+ if (targets.length === 0) {
683
+ io.stdout("Nothing to change.\n");
684
+ return 0;
685
+ }
686
+ if (pattern && !values.yes) {
687
+ io.stdout(`${verb} ${plural(targets.length, "key")} ${mode === "add" ? "with" : "from"} ${release.name}:\n`);
688
+ for (const state of targets) io.stdout(` ${state.key}\n`);
689
+ const answer = io.prompt ? await io.prompt("Proceed? [y/N] ") : "";
690
+ if (!/^y(es)?$/i.test(answer.trim())) {
691
+ io.stdout("Nothing changed; pass --yes to skip this question.\n");
692
+ return 0;
693
+ }
694
+ }
695
+ const { changed } = await client.setReleaseMembership({
696
+ releaseId: id,
697
+ keyIds: targets.map((state) => state.id),
698
+ mode
699
+ });
700
+ if (values.json) io.stdout(`${JSON.stringify({
701
+ release: release.name,
702
+ mode,
703
+ keys: targets.map((state) => state.key),
704
+ changed
705
+ }, null, 2)}\n`);
706
+ else io.stdout(`${verb}led ${plural(changed, "key")} ${mode === "add" ? "with" : "from"} ${release.name}.\n`);
707
+ return 0;
708
+ }
709
+ async function runReleases(io, values, [action = "list", ...args]) {
710
+ const { client, loaded } = await loadProject(io, values);
711
+ const current = loaded.config.release;
712
+ switch (action) {
713
+ case "list": {
714
+ const { releases } = await releasesOf(client);
715
+ if (values.json) io.stdout(`${JSON.stringify({
716
+ current: current ?? null,
717
+ releases
718
+ }, null, 2)}\n`);
719
+ else if (releases.length === 0) io.stdout("The project has no releases.\n");
720
+ else {
721
+ const mark = current && findRelease(releases, current);
722
+ for (const release of releases) io.stdout(`${release === mark ? "*" : " "} ${release.name}\n`);
723
+ if (current && !mark) io.stdout(`The config names "${current}", which is not one.\n`);
724
+ }
725
+ return 0;
726
+ }
727
+ case "use": {
728
+ if (values.none) return use(io, loaded, null, values.json);
729
+ const { releases } = await releasesOf(client);
730
+ return use(io, loaded, args[0] ? requireRelease(releases, args[0]) : await choose(io, releases), values.json);
731
+ }
732
+ case "create": {
733
+ const name = args[0]?.trim();
734
+ if (!name) throw new Error(`Name the release.\n${USAGE$1}`);
735
+ const release = await client.createRelease(name).catch((error) => {
736
+ if (error instanceof LocalnessError && error.code === "forbidden") throw new Error("Only project owners can create releases.");
737
+ throw error;
738
+ });
739
+ if (values.use) await writeConfigFields(loaded.path, { release: release.name });
740
+ io.stdout(values.json ? `${JSON.stringify({
741
+ ...release,
742
+ used: values.use ?? false
743
+ }, null, 2)}\n` : `Created release ${release.name}${values.use ? "; new keys will be labelled with it" : ""}.\n`);
744
+ return 0;
745
+ }
746
+ case "add":
747
+ case "remove": return label(io, values, client, action, args);
748
+ default: throw new Error(`Unknown releases action: ${action}.\n${USAGE$1}`);
749
+ }
750
+ }
751
+ // src/review/server.ts
752
+ const MAX_BODY = 1048576;
753
+ function readBody(request) {
754
+ return new Promise((resolve, reject) => {
755
+ let size = 0;
756
+ const chunks = [];
757
+ request.on("data", (chunk) => {
758
+ size += chunk.length;
759
+ if (size > MAX_BODY) {
760
+ reject(/* @__PURE__ */ new Error("Request too large."));
761
+ request.destroy();
762
+ } else chunks.push(chunk);
763
+ });
764
+ request.on("end", () => {
765
+ try {
766
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "null"));
767
+ } catch {
768
+ reject(/* @__PURE__ */ new Error("Invalid JSON."));
769
+ }
770
+ });
771
+ request.on("error", reject);
772
+ });
773
+ }
774
+ /**
775
+ * Serves the review page on 127.0.0.1 at a random port. Every request must
776
+ * carry the URL's token, so other local pages cannot read or answer it.
777
+ */
778
+ async function startReviewServer(options) {
779
+ const token = randomBytes(16).toString("hex");
780
+ const session = createReviewSession(options);
781
+ const server = createServer(async (request, response) => {
782
+ const send = (status, body, type = "application/json") => {
783
+ response.writeHead(status, {
784
+ "content-type": `${type}; charset=utf-8`,
785
+ "cache-control": "no-store"
786
+ });
787
+ response.end(type === "application/json" ? JSON.stringify(body) : body);
788
+ };
789
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
790
+ if ((url.searchParams.get("t") ?? request.headers["x-review-token"]) !== token) return send(403, { error: "Wrong review token." });
791
+ if (request.method === "GET" && url.pathname === "/") return send(200, reviewPage({
792
+ host: "browser",
793
+ token
794
+ }), "text/html");
795
+ let body;
796
+ try {
797
+ body = request.method === "POST" ? await readBody(request) : void 0;
798
+ } catch (error) {
799
+ return send(400, { error: error instanceof Error ? error.message : String(error) });
800
+ }
801
+ const answer = await session.request(request.method ?? "GET", url.pathname, body);
802
+ return send(answer.status, answer.body);
803
+ });
804
+ await new Promise((resolve, reject) => {
805
+ server.once("error", reject);
806
+ server.listen(0, "127.0.0.1", resolve);
807
+ });
808
+ const { port } = server.address();
809
+ return {
810
+ server,
811
+ url: `http://127.0.0.1:${port}/?t=${token}`,
812
+ done: session.done
813
+ };
814
+ }
815
+ // src/review/index.ts
816
+ const USAGE = "Usage: localness review start <file> [--open auto|browser|editor] | localness review wait <id> [--timeout <seconds>]";
817
+ const OPEN_MODES = [
818
+ "auto",
819
+ "browser",
820
+ "editor"
821
+ ];
822
+ const START_WAIT_MS = 15e3;
823
+ const CLAIM_WAIT_MS = 3e3;
824
+ const DEFAULT_WAIT_S = 90;
825
+ const SERVE_TTL_MS = 72e5;
826
+ async function waitForClaim(path, ms) {
827
+ for (let waited = 0; waited < ms; waited += 200) {
828
+ await setTimeout$1(200);
829
+ const claim = await readJson(path).catch(() => null);
830
+ if (claim) return claim;
831
+ }
832
+ return null;
833
+ }
834
+ async function snippetOf(path, line) {
835
+ if (!line) return void 0;
836
+ const text = (await readFile(path, "utf8").catch(() => null))?.split(/\r?\n/)[line - 1]?.trim();
837
+ return text ? text.slice(0, 200) : void 0;
838
+ }
839
+ function editorOf(env) {
840
+ return env.CURSOR_TRACE_ID || env.CURSOR_AGENT || /cursor/i.test(env.VSCODE_GIT_ASKPASS_MAIN ?? "") ? "cursor" : "vscode";
841
+ }
842
+ function openBrowser(url) {
843
+ const [command, args] = process.platform === "win32" ? ["explorer.exe", [url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
844
+ const child = spawn(command, args, {
845
+ detached: true,
846
+ stdio: "ignore"
847
+ });
848
+ child.on("error", () => {});
849
+ child.unref();
850
+ }
851
+ async function runStart(io, values, file) {
852
+ const open = values.open ?? "auto";
853
+ if (!OPEN_MODES.includes(open)) throw new Error("--open takes auto, browser or editor.");
854
+ const input = parseReviewInput(JSON.parse(await readFile(resolve(io.cwd, file), "utf8")));
855
+ const { loaded, meta, matches } = await lookupTexts(io, values, input.map((item) => item.text));
856
+ const now = Date.now();
857
+ await prepareReviewDir(loaded.root, now);
858
+ const inEditor = open !== "browser" && await hasEditor(loaded.root);
859
+ if (open === "editor" && !inEditor) throw new Error("No VS Code or Cursor window with the Localness extension has this project open.");
860
+ const id = randomBytes(4).toString("hex");
861
+ const rows = await Promise.all(input.map(async (item, index) => {
862
+ const path = item.file ? resolve(io.cwd, item.file) : void 0;
863
+ return {
864
+ index: index + 1,
865
+ text: item.text,
866
+ file: item.file,
867
+ line: item.line,
868
+ path,
869
+ snippet: path ? await snippetOf(path, item.line) : void 0,
870
+ candidates: matches[index].keys.map((hit) => ({
871
+ key: hit.key,
872
+ sourceText: hit.sourceText,
873
+ source: hit.source,
874
+ ...hit.source === "platform" && hit.draft && { draft: true }
875
+ })),
876
+ suggestion: item.key?.trim() ?? ""
877
+ };
878
+ }));
879
+ const doc = {
880
+ id,
881
+ createdAt: new Date(now).toISOString(),
882
+ project: meta.project?.name ?? String(loaded.config.project ?? ""),
883
+ sourceLocale: meta.sourceLocale ?? "",
884
+ editor: editorOf(io.env),
885
+ convention: meta.keyConvention ?? null,
886
+ namespaces: (meta.namespaces ?? []).map((namespace) => namespace.name),
887
+ rows,
888
+ open: inEditor ? "editor" : "browser"
889
+ };
890
+ const files = reviewPaths(loaded.root, id);
891
+ await writeJson(files.doc, doc);
892
+ let claim = inEditor ? await waitForClaim(files.claim, open === "editor" ? START_WAIT_MS : CLAIM_WAIT_MS) : null;
893
+ if (!claim && open === "editor") throw new Error("The editor did not open the review; try --open browser.");
894
+ claim ??= await serveInBrowser(io, values, id, files.claim);
895
+ if (!claim?.url && !claim?.editor) throw new Error(claim?.error ?? "The review page did not start; check the review file.");
896
+ if (claim.url) openBrowser(claim.url);
897
+ const openedIn = claim.url ? "browser" : "editor";
898
+ if (values.json) io.stdout(`${JSON.stringify({
899
+ id,
900
+ url: claim.url ?? null,
901
+ rows: rows.length,
902
+ openedIn
903
+ })}\n`);
904
+ else {
905
+ const where = claim.url ? `opened in the browser:\n ${claim.url}` : "opened in your editor.";
906
+ io.stdout(`Review ${id}: ${plural(rows.length, "text")}, ${where}\nRun "localness review wait ${id}" for the decisions.\n`);
907
+ }
908
+ return 0;
909
+ }
910
+ function serveInBrowser(io, values, id, claimPath) {
911
+ const args = [
912
+ process.argv[1],
913
+ "review",
914
+ "serve",
915
+ id
916
+ ];
917
+ if (values.config) args.push("--config", resolve(io.cwd, values.config));
918
+ spawn(process.execPath, args, {
919
+ cwd: io.cwd,
920
+ env: io.env,
921
+ detached: true,
922
+ stdio: "ignore",
923
+ windowsHide: true
924
+ }).unref();
925
+ return waitForClaim(claimPath, START_WAIT_MS);
926
+ }
927
+ async function runServe(io, values, id) {
928
+ const { loaded, client } = await loadProject(io, values);
929
+ const files = reviewPaths(loaded.root, id);
930
+ try {
931
+ const doc = await readJson(files.doc);
932
+ if (!doc) throw new Error(`No review ${id}.`);
933
+ const review = await startReviewServer({
934
+ doc,
935
+ taken: takenNames(loaded, client, doc.sourceLocale),
936
+ onDone: (result) => writeJson(files.result, result)
937
+ });
938
+ const close = () => {
939
+ review.server.close();
940
+ review.server.closeAllConnections();
941
+ };
942
+ if (!await claimReview(files.claim, {
943
+ url: review.url,
944
+ pid: process.pid
945
+ })) {
946
+ close();
947
+ return 0;
948
+ }
949
+ const expire = setTimeout(async () => {
950
+ await writeJson(files.result, {
951
+ id,
952
+ status: "cancelled",
953
+ items: []
954
+ });
955
+ close();
956
+ }, SERVE_TTL_MS);
957
+ await Promise.race([review.done, new Promise((done) => review.server.once("close", done))]);
958
+ clearTimeout(expire);
959
+ close();
960
+ return 0;
961
+ } catch (error) {
962
+ await claimReview(files.claim, { error: error instanceof Error ? error.message : String(error) });
963
+ throw error;
964
+ }
965
+ }
966
+ async function runWait(io, values, id) {
967
+ const timeout = values.timeout === void 0 ? DEFAULT_WAIT_S : Number(values.timeout);
968
+ if (!Number.isFinite(timeout) || timeout < 0) throw new Error("--timeout takes a number of seconds.");
969
+ const config = values.config ?? await findConfigFile(io.cwd);
970
+ if (!config) throw new Error("No localness.config.json here or above.");
971
+ const files = reviewPaths((await loadConfig(config)).root, id);
972
+ const until = Date.now() + timeout * 1e3;
973
+ for (;;) {
974
+ const result = await readJson(files.result);
975
+ if (result) {
976
+ io.stdout(`${JSON.stringify(result, null, 2)}\n`);
977
+ return 0;
978
+ }
979
+ const info = await readJson(files.claim);
980
+ if (!info) throw new Error(`No review ${id} here.`);
981
+ if (!isAlive(info.pid)) {
982
+ const shown = info.editor ? "The editor showing" : "The review page for";
983
+ throw new Error(`${shown} ${id} stopped without an answer; start a new review.`);
984
+ }
985
+ if (Date.now() >= until) {
986
+ io.stdout(`${JSON.stringify({
987
+ id,
988
+ status: "pending",
989
+ url: info.url
990
+ }, null, 2)}\n`);
991
+ io.stderr(`Nothing decided yet; run "localness review wait ${id}" again.\n`);
992
+ return 0;
993
+ }
994
+ await setTimeout$1(500);
995
+ }
996
+ }
997
+ /** An interactive page where the person decides, per extracted text, which key it gets. */
998
+ async function runReview(io, values, [sub, arg, ...extra]) {
999
+ if (!sub || !arg || extra.length > 0) throw new Error(USAGE);
1000
+ switch (sub) {
1001
+ case "start": return runStart(io, values, arg);
1002
+ case "wait": return runWait(io, values, arg);
1003
+ case "serve": return runServe(io, values, arg);
1004
+ default: throw new Error(USAGE);
1005
+ }
1006
+ }
1007
+ // src/skill.ts
1008
+ const SKILL_NAME = "localness";
1009
+ const TEMPLATE_DIR = fileURLToPath(new URL("../skill/", import.meta.url));
1010
+ const SKILL_FILE = "SKILL.md";
1011
+ const REFERENCES = "references";
1012
+ /** Folders each agent reads project skills from, its own first. */
1013
+ const AGENT_READS = {
1014
+ copilot: [
1015
+ ".github/skills",
1016
+ ".claude/skills",
1017
+ ".agents/skills"
1018
+ ],
1019
+ claude: [".claude/skills"],
1020
+ cursor: [
1021
+ ".cursor/skills",
1022
+ ".claude/skills",
1023
+ ".agents/skills"
1024
+ ],
1025
+ codex: [".agents/skills"]
1026
+ };
1027
+ const AGENTS = Object.keys(AGENT_READS);
1028
+ const DEFAULT_AGENTS = [
1029
+ "copilot",
1030
+ "claude",
1031
+ "cursor"
1032
+ ];
1033
+ /** Tie-break order: the vendor-neutral folder first. */
1034
+ const SKILL_DIRS = [
1035
+ ".agents/skills",
1036
+ ".claude/skills",
1037
+ ".github/skills",
1038
+ ".cursor/skills"
1039
+ ];
1040
+ /**
1041
+ * The fewest folders every agent reads from: one copy per agent would show the
1042
+ * skill twice to agents that read several folders.
1043
+ */
1044
+ function skillDirsFor(agents) {
1045
+ const left = new Set(agents);
1046
+ const dirs = [];
1047
+ while (left.size > 0) {
1048
+ let best = "";
1049
+ let bestScore = 0;
1050
+ for (const dir of SKILL_DIRS) {
1051
+ const readers = [...left].filter((agent) => AGENT_READS[agent].includes(dir));
1052
+ const own = readers.some((agent) => AGENT_READS[agent][0] === dir);
1053
+ const score = readers.length + (own ? .5 : 0);
1054
+ if (score > bestScore) {
1055
+ best = dir;
1056
+ bestScore = score;
1057
+ }
1058
+ }
1059
+ dirs.push(best);
1060
+ for (const agent of left) if (AGENT_READS[agent].includes(best)) left.delete(agent);
1061
+ }
1062
+ return dirs;
1063
+ }
1064
+ function parseAgents(value) {
1065
+ const names = list(value);
1066
+ if (!names) return DEFAULT_AGENTS;
1067
+ if (names.includes("all")) return AGENTS;
1068
+ for (const name of names) if (!AGENTS.includes(name)) throw new Error(`Unknown agent: ${name}. Use ${AGENTS.join(", ")} or all.`);
1069
+ return names;
1070
+ }
1071
+ const HASH_FIELD = /localness-hash: ["'][^"']*["']/;
1072
+ const VERSION_FIELD = /localness-cli: ["']([^"']*)["']/;
1073
+ const normalize = (text) => text.replace(/\r\n/g, "\n");
1074
+ /**
1075
+ * Over SKILL.md without its own hash, then every reference, ignoring line
1076
+ * endings git may change. Without references it is the hash of SKILL.md
1077
+ * alone, as single-file installs recorded it.
1078
+ */
1079
+ function hashOf(files) {
1080
+ const hash = createHash("sha256").update(normalize(files.get(SKILL_FILE) ?? "").replace(HASH_FIELD, "localness-hash: ''"));
1081
+ const references = [...files.keys()].filter((path) => path !== SKILL_FILE);
1082
+ for (const path of references.sort()) hash.update(`\0${path}\n${normalize(files.get(path))}`);
1083
+ return hash.digest("hex").slice(0, 16);
1084
+ }
1085
+ /** SKILL.md and the files under `references/`; null without SKILL.md. */
1086
+ async function readSkillFolder(dir) {
1087
+ const skill = await readOptional(join(dir, SKILL_FILE));
1088
+ if (skill === null) return null;
1089
+ const files = /* @__PURE__ */ new Map([[SKILL_FILE, skill]]);
1090
+ const entries = await readdir(join(dir, REFERENCES), { withFileTypes: true }).catch((error) => {
1091
+ if (error.code === "ENOENT") return [];
1092
+ throw error;
1093
+ });
1094
+ for (const entry of entries) {
1095
+ if (!entry.isFile()) continue;
1096
+ const path = `${REFERENCES}/${entry.name}`;
1097
+ files.set(path, await readFile(join(dir, REFERENCES, entry.name), "utf8"));
1098
+ }
1099
+ return files;
1100
+ }
1101
+ async function renderSkill() {
1102
+ const files = await readSkillFolder(TEMPLATE_DIR);
1103
+ for (const [path, text] of files) files.set(path, normalize(text));
1104
+ files.set(SKILL_FILE, files.get(SKILL_FILE).replace("{{version}}", version));
1105
+ const hash = hashOf(files);
1106
+ files.set(SKILL_FILE, files.get(SKILL_FILE).replace(HASH_FIELD, `localness-hash: '${hash}'`));
1107
+ return files;
1108
+ }
1109
+ function readInstalledSkill(files) {
1110
+ const text = files.get(SKILL_FILE) ?? "";
1111
+ const hash = /localness-hash: ["']([0-9a-f]*)["']/.exec(text)?.[1];
1112
+ return {
1113
+ version: VERSION_FIELD.exec(text)?.[1] ?? null,
1114
+ modified: !hash || hash !== hashOf(files)
1115
+ };
1116
+ }
1117
+ function sameFiles(a, b) {
1118
+ return a.size === b.size && [...a].every(([path, text]) => normalize(b.get(path) ?? "\0") === text);
1119
+ }
1120
+ async function exists(path) {
1121
+ return stat(path).then(() => true, () => false);
1122
+ }
1123
+ async function readOptional(path) {
1124
+ return readFile(path, "utf8").catch((error) => {
1125
+ if (error.code === "ENOENT") return null;
1126
+ throw error;
1127
+ });
1128
+ }
1129
+ /** The git root above `dir`, where agents look for skills; else `dir`. */
1130
+ async function repoRoot(dir) {
1131
+ for (let current = dir;;) {
1132
+ if (await exists(join(current, ".git"))) return current;
1133
+ const parent = dirname(current);
1134
+ if (parent === current) return dir;
1135
+ current = parent;
1136
+ }
1137
+ }
1138
+ async function startDir(io, values) {
1139
+ const config = values.config ?? await findConfigFile(io.cwd);
1140
+ return config ? dirname(resolve(io.cwd, config)) : io.cwd;
1141
+ }
1142
+ async function rootFor(io, values) {
1143
+ if (values.root) return resolve(io.cwd, values.root);
1144
+ return repoRoot(await startDir(io, values));
1145
+ }
1146
+ function skillFolder(root, dir) {
1147
+ return join(root, ...dir.split("/"), SKILL_NAME);
1148
+ }
1149
+ /** Installed copies under `root`, in any folder an agent reads. */
1150
+ async function findInstalledSkills(root) {
1151
+ const found = [];
1152
+ for (const dir of SKILL_DIRS) {
1153
+ const folder = skillFolder(root, dir);
1154
+ const files = await readSkillFolder(folder);
1155
+ if (files !== null) {
1156
+ const path = join(folder, SKILL_FILE);
1157
+ found.push({
1158
+ dir,
1159
+ path,
1160
+ skill: readInstalledSkill(files)
1161
+ });
1162
+ }
1163
+ }
1164
+ return found;
1165
+ }
1166
+ /** One line on stderr when an installed copy came from another CLI version. */
1167
+ async function warnOutdatedSkill(io, values) {
1168
+ const start = await startDir(io, values);
1169
+ const root = await repoRoot(start);
1170
+ for (let dir = start;; dir = dirname(dir)) {
1171
+ const outdated = (await findInstalledSkills(dir)).find(({ skill }) => skill.version !== null && skill.version !== version);
1172
+ if (outdated) {
1173
+ const flag = dir === root ? "" : ` --root ${relative(io.cwd, dir) || "."}`;
1174
+ io.stderr(`localness: the Agent Skill in ${relative(io.cwd, dirname(outdated.path)) || "."} is for CLI ${outdated.skill.version}, this is ${version}; run "localness skill install${flag}" to update it.\n`);
1175
+ return;
1176
+ }
1177
+ if (dir === root || dirname(dir) === dir) return;
1178
+ }
1179
+ }
1180
+ const AGENTS_MD = "AGENTS.md";
1181
+ const BLOCK_START = "<!-- localness:start -->";
1182
+ const BLOCK_END = "<!-- localness:end -->";
1183
+ function agentsBlock(skillFile) {
1184
+ return `${BLOCK_START}
1185
+ ## Localness
1186
+
1187
+ The locale JSON files are synced with a Localness project. Before changing them, read \`${skillFile}\` and follow it: move text only with the \`localness\` CLI, show a person the plan before \`localness apply\`, and never settle a conflict on your own.
1188
+ ${BLOCK_END}`;
1189
+ }
1190
+ /** Replaces the marked block, or appends one. */
1191
+ function withAgentsBlock(text, block) {
1192
+ if (text === null) return `${block}\n`;
1193
+ const start = text.indexOf(BLOCK_START);
1194
+ const end = text.indexOf(BLOCK_END);
1195
+ if (start !== -1 && end > start) return `${text.slice(0, start)}${block}${text.slice(end + 22)}`;
1196
+ return `${text.replace(/\s*$/, "")}\n\n${block}\n`;
1197
+ }
1198
+ async function runSkill(io, values, subcommand) {
1199
+ if (subcommand !== "install") throw new Error(`Unknown skill command: ${subcommand ?? "(none)"}. Run "localness skill install".`);
1200
+ const agents = parseAgents(values.agent);
1201
+ const root = await rootFor(io, values);
1202
+ const content = await renderSkill();
1203
+ const dryRun = values["dry-run"] ?? false;
1204
+ const force = values.force ?? false;
1205
+ const installed = await findInstalledSkills(root);
1206
+ const dirs = [.../* @__PURE__ */ new Set([...skillDirsFor(agents), ...installed.map(({ dir }) => dir)])];
1207
+ const results = [];
1208
+ for (const dir of dirs) {
1209
+ const folder = skillFolder(root, dir);
1210
+ const current = await readSkillFolder(folder);
1211
+ let action;
1212
+ if (current === null) action = "created";
1213
+ else if (sameFiles(content, current)) action = "unchanged";
1214
+ else if (readInstalledSkill(current).modified && !force) action = "modified";
1215
+ else action = "updated";
1216
+ if (!dryRun && (action === "created" || action === "updated")) {
1217
+ for (const path of current?.keys() ?? []) if (!content.has(path)) await rm(join(folder, path), { force: true });
1218
+ for (const [path, text] of content) {
1219
+ const target = join(folder, path);
1220
+ await mkdir(dirname(target), { recursive: true });
1221
+ await writeFile(target, text, "utf8");
1222
+ }
1223
+ }
1224
+ results.push({
1225
+ path: relative(io.cwd, join(folder, SKILL_FILE)),
1226
+ action
1227
+ });
1228
+ }
1229
+ let agentsMd = null;
1230
+ if (values["agents-md"]) {
1231
+ const path = join(root, AGENTS_MD);
1232
+ const skillFile = relative(root, join(skillFolder(root, dirs[0]), SKILL_FILE)).replace(/\\/g, "/");
1233
+ const current = await readOptional(path);
1234
+ const next = withAgentsBlock(current, agentsBlock(skillFile));
1235
+ if (!dryRun && next !== current) await writeFile(path, next, "utf8");
1236
+ agentsMd = relative(io.cwd, path);
1237
+ }
1238
+ const refused = results.filter(({ action }) => action === "modified");
1239
+ if (values.json) io.stdout(`${JSON.stringify({
1240
+ version,
1241
+ agents,
1242
+ dryRun,
1243
+ skills: results,
1244
+ agentsMd
1245
+ }, null, 2)}\n`);
1246
+ else {
1247
+ for (const { path, action } of results) io.stdout(action === "modified" ? ` kept ${path}: edited by hand; --force overwrites it\n` : ` ${dryRun && action !== "unchanged" ? `would be ${action}` : action} ${path}\n`);
1248
+ if (agentsMd) io.stdout(` ${dryRun ? "would update" : "updated"} ${agentsMd}\n`);
1249
+ io.stdout(dryRun ? `Dry run: Agent Skill ${version} for ${agents.join(", ")}.\n` : `Agent Skill ${version} for ${agents.join(", ")}. Commit it so every checkout's agents get it.\n`);
1250
+ }
1251
+ return refused.length > 0 ? 2 : 0;
1252
+ }
1253
+ // src/suggest-name.ts
1254
+ /** Asks the project's AI naming; writes nothing. */
1255
+ async function runSuggestName(io, values, text) {
1256
+ if (!text.trim()) throw new Error("Usage: localness suggest-name \"<source text>\"");
1257
+ const { client } = await loadProject(io, values);
1258
+ const suggestion = await client.suggestKeyName(text);
1259
+ if (values.json) {
1260
+ io.stdout(`${JSON.stringify(suggestion, null, 2)}\n`);
1261
+ return 0;
1262
+ }
1263
+ if (!suggestion.key) {
1264
+ io.stdout("No name: the text has nothing to name.\n");
1265
+ return 0;
1266
+ }
1267
+ const confidence = suggestion.confidence === void 0 ? "" : ` (confidence ${suggestion.confidence})`;
1268
+ io.stdout(`${suggestion.key}${confidence}\n`);
1269
+ if (suggestion.alternatives?.length) io.stdout(`Alternatives: ${suggestion.alternatives.map((item) => item.key).join(", ")}\n`);
1270
+ if (suggestion.violations.length > 0) io.stdout(`Breaks the project's key convention: ${suggestion.violations.join(", ")}\n`);
1271
+ for (const duplicate of suggestion.duplicates) io.stdout(`Already in the project: ${duplicate.key} ${JSON.stringify(duplicate.sourceText)}${duplicate.sameSourceText ? ", same text; reuse it" : ""}\n`);
1272
+ if (suggestion.reason) io.stdout(`${suggestion.reason}\n`);
1273
+ return 0;
1274
+ }
1275
+ // src/sync.ts
1276
+ /** Pulls the project's changes and plans pushing local ones; `apply` stays separate. */
1277
+ async function runSync(io, values) {
1278
+ const { client, loaded } = await loadProject(io, values);
1279
+ const comparison = await compareLocaleFiles(loaded, client, {
1280
+ locales: list(values.locales),
1281
+ keys: list(values.keys)
1282
+ });
1283
+ const dryRun = values["dry-run"] ?? false;
1284
+ const pulled = await pullInto(loaded, comparison, {
1285
+ kinds: SYNC_PULL_KINDS,
1286
+ prune: false,
1287
+ dryRun
1288
+ });
1289
+ const pushed = await planPushFrom(io, loaded, client, comparison, {
1290
+ kinds: PUSH_KINDS,
1291
+ dryRun
1292
+ });
1293
+ if (values.json) io.stdout(`${JSON.stringify({
1294
+ pull: pullJson(pulled, dryRun),
1295
+ push: pushJson(pushed)
1296
+ }, null, 2)}\n`);
1297
+ else {
1298
+ describePull(io, pulled, dryRun);
1299
+ describePush(io, pushed, dryRun);
1300
+ }
1301
+ return 0;
1302
+ }
1303
+ // src/run.ts
1304
+ const SYNC_COMMANDS = /* @__PURE__ */ new Set([
1305
+ "diff",
1306
+ "pull",
1307
+ "push",
1308
+ "apply",
1309
+ "sync"
1310
+ ]);
1311
+ const HELP = `localness ${version}: sync locale JSON files with a Localness project
1312
+
1313
+ Usage: localness <command> [options]
1314
+
1315
+ Commands:
1316
+ init Find the repository's locale files and write localness.config.json
1317
+ diff Compare the locale files with the project (exit 1 when they differ)
1318
+ pull Write the project's changes into the locale files
1319
+ push Plan sending local changes to the project; writes nothing
1320
+ apply <id> Write a plan to the project (no id: list plans)
1321
+ sync pull the project's changes, then plan a push of local ones
1322
+ match <text...> Existing keys whose source text equals each text
1323
+ suggest-name <text> Ask the project's AI for a key name; writes nothing
1324
+ review start <file> Open a page to decide, per extracted text, which key it
1325
+ gets (reuse, new or skip): in the editor when the
1326
+ Localness extension has the project open, else the browser
1327
+ review wait <id> Print the decisions once approved (JSON; "pending" after
1328
+ --timeout)
1329
+ releases [use|create|add|remove]
1330
+ List releases, pick the one new keys get, create one,
1331
+ or label existing keys
1332
+ skill install Install the Agent Skill that teaches coding agents
1333
+ this workflow, at the repository root
1334
+
1335
+ Options:
1336
+ --config <path> Config file (default: nearest localness.config.json)
1337
+ --keys <a,b> Only these keys; for pull and push, take that side even
1338
+ when both changed
1339
+ --locales <en,ja> Only these platform locales
1340
+ --prune Also remove keys the project does not have (pull)
1341
+ --dry-run Show what would happen (init, pull, push, sync, skill)
1342
+ --json Machine-readable output
1343
+ --base-url <url> Localness instance URL (init)
1344
+ --project <name|id> Project (init; default: the token's only project)
1345
+ --dir <path> Locale directory, skipping detection (init)
1346
+ --pattern <pattern> File pattern under --dir, e.g. {locale}.json (init)
1347
+ --format <format> flat-json or nested-json (init)
1348
+ --force Overwrite an existing config (init) or a hand-edited
1349
+ Skill (skill install)
1350
+ --agent <a,b> Agents the Skill is for: copilot, claude, cursor, codex
1351
+ or all (default: copilot,claude,cursor)
1352
+ --agents-md Also point AGENTS.md at the Skill (skill install)
1353
+ --root <path> Folder the agents open, when it is not the git root
1354
+ (skill install)
1355
+ --release <name> Release new keys are labelled with (init)
1356
+ --none No release for new keys (releases use)
1357
+ --use Also use the release created (releases create)
1358
+ --match <glob> Keys to label, e.g. "checkout.*" (releases add/remove)
1359
+ --timeout <seconds> How long review wait waits (default 90)
1360
+ --open <where> Where review start shows the page: auto (default),
1361
+ browser or editor
1362
+ -y, --yes Skip the confirmation of --match
1363
+ -h, --help Show this help
1364
+ -v, --version Show the version
1365
+
1366
+ The token is ${TOKEN_ENV} from .env.local next to the config, else from the
1367
+ environment. Reading needs a read token; apply and suggest-name need
1368
+ a read & write token. "release" in the config labels the keys push and apply
1369
+ create; existing keys keep their labels. pull, sync and apply keep .localness/ next to the config:
1370
+ the last agreed text and pending plans, never committed.
1371
+ `;
1372
+ function describe(error) {
1373
+ if (!(error instanceof LocalnessError)) return error instanceof Error ? error.message : String(error);
1374
+ const detail = error.serverMessage ? ` (${error.serverMessage})` : "";
1375
+ switch (error.code) {
1376
+ case "auth": return `Authentication failed; check ${TOKEN_ENV}.`;
1377
+ case "forbidden": return `The token may not do this${detail}; ${TOKEN_ENV} needs a read & write token.`;
1378
+ case "ambiguous-project": return "The project name matches more than one project; set \"project\" to its id.";
1379
+ case "bad-request": return `The server rejected the request${detail}. A token that reaches several projects needs "project" in the config.`;
1380
+ default: return `${error.message}${detail}`;
1381
+ }
1382
+ }
1383
+ async function run(argv, io) {
1384
+ try {
1385
+ const { values, positionals } = parseArgs({
1386
+ args: argv,
1387
+ options: OPTIONS,
1388
+ allowPositionals: true
1389
+ });
1390
+ const [command, ...rest] = positionals;
1391
+ if (values.version) {
1392
+ io.stdout(`${version}\n`);
1393
+ return 0;
1394
+ }
1395
+ if (values.help || !command) {
1396
+ io.stdout(HELP);
1397
+ return values.help ? 0 : 2;
1398
+ }
1399
+ if (command === "suggest-name") return await runSuggestName(io, values, rest.join(" "));
1400
+ if (command === "match") return await runMatch(io, values, rest);
1401
+ if (command === "releases") return await runReleases(io, values, rest);
1402
+ if (command === "review") return await runReview(io, values, rest);
1403
+ const allowed = command === "apply" || command === "skill" ? 1 : 0;
1404
+ if (rest.length > allowed) throw new Error(`Unexpected argument: ${rest[allowed]}`);
1405
+ if (SYNC_COMMANDS.has(command)) await warnOutdatedSkill(io, values).catch(() => {});
1406
+ switch (command) {
1407
+ case "init": return await runInit(io, values);
1408
+ case "diff": return await runDiff(io, values);
1409
+ case "pull": return await runPull(io, values);
1410
+ case "push": return await runPush(io, values);
1411
+ case "apply": return await runApply(io, values, rest[0]);
1412
+ case "sync": return await runSync(io, values);
1413
+ case "skill": return await runSkill(io, values, rest[0]);
1414
+ default: throw new Error(`Unknown command: ${command}. Run "localness --help".`);
1415
+ }
1416
+ } catch (error) {
1417
+ io.stderr(`localness: ${describe(error)}\n`);
1418
+ return 2;
1419
+ }
1420
+ }
1421
+ // src/cli.ts
1422
+ async function prompt(question) {
1423
+ const rl = createInterface({
1424
+ input: process.stdin,
1425
+ output: process.stdout
1426
+ });
1427
+ try {
1428
+ return await rl.question(question);
1429
+ } finally {
1430
+ rl.close();
1431
+ }
1432
+ }
1433
+ process.exitCode = await run(process.argv.slice(2), {
1434
+ cwd: process.cwd(),
1435
+ env: process.env,
1436
+ stdout: (text) => process.stdout.write(text),
1437
+ stderr: (text) => process.stderr.write(text),
1438
+ prompt: process.stdin.isTTY && process.stdout.isTTY ? prompt : void 0
1439
+ });
1440
+ export {};