@menapo/vi18n 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +19 -0
  2. package/dist/{apply-FAHl1R6T.js → apply-Bg-3rB2m.js} +4 -4
  3. package/dist/{captured-CTjjDF5o.js → captured-DfLk50Ji.js} +1 -1
  4. package/dist/{check-DwFwOB1d.js → check-CunekuYs.js} +16 -7
  5. package/dist/cli.js +1 -1
  6. package/dist/{collisions-uMTuq36M.js → collisions-CDSdtLQm.js} +2 -2
  7. package/dist/{compile-CEvH-6sY.js → compile-hva0qjhZ.js} +6 -6
  8. package/dist/config.d.ts +1 -1
  9. package/dist/config.js +2 -2
  10. package/dist/{diagnostics-1onDF6Ua.js → diagnostics-LgIWyeSp.js} +2 -1
  11. package/dist/{duplicates-CsUXRX2J.js → duplicates-8cudcHNj.js} +1 -1
  12. package/dist/{engine-Bf7nVigL.js → engine-ecRD8-IE.js} +11 -11
  13. package/dist/engine.d.ts +1 -1
  14. package/dist/{exchange-DYG9RZoT.js → exchange-DjwlrTQ9.js} +3 -3
  15. package/dist/{exclude-vMnm3lqU.js → exclude-BFETmvde.js} +1 -1
  16. package/dist/{export-BYq0gfLd.js → export-D2tsqWIr.js} +6 -6
  17. package/dist/{extract-CYtuEo8u.js → extract-BxYchVmY.js} +7 -7
  18. package/dist/{formats-ChV1LVH_.js → formats-BaryZ2N7.js} +3 -3
  19. package/dist/{i18next-D66Icz3L.js → i18next-COO6o0tX.js} +6 -6
  20. package/dist/i18next-Dr7DCQlQ.js +1 -0
  21. package/dist/{import-BApbQlmm.js → import-vSC29Cn4.js} +6 -6
  22. package/dist/index.d.ts +1 -1
  23. package/dist/{init-J7AwwA5e.js → init-Cc7A-8VX.js} +9 -9
  24. package/dist/{library-BfSOBeBd.js → library-tp_xqzSY.js} +2 -2
  25. package/dist/{lingui-Ee2farVo.js → lingui-BnnlqGXT.js} +8 -8
  26. package/dist/lint.js +7 -6
  27. package/dist/{load-BFLLqY8x.js → load-BSIeGJ5v.js} +8 -6
  28. package/dist/{load-CMwhukZ4.js → load-SSrAeJVB.js} +5 -3
  29. package/dist/{locales-DxLDrx-h.js → locales-D0U-yVRm.js} +4 -4
  30. package/dist/{lsp-BC7xDGON.js → lsp-DvC11pBZ.js} +2 -2
  31. package/dist/{mcp-Cka8ywDF.js → mcp-D2zzOTBy.js} +2 -2
  32. package/dist/{merge-driver-B04Apm29.js → merge-driver-BLI8OtAc.js} +6 -6
  33. package/dist/migrate-1r43OBfe.js +1 -0
  34. package/dist/{migrate-D7TNl6SD.js → migrate-ChDGhlC-.js} +11 -11
  35. package/dist/{openai-RWw0YlAx.js → openai-CLn4puY8.js} +1 -1
  36. package/dist/{output-CF9uvk_-.js → output-D5tAt8q4.js} +3 -3
  37. package/dist/parse.d.ts +1 -1
  38. package/dist/{pipeline-sgl_q_op.js → pipeline-BJSkkRYC.js} +7 -7
  39. package/dist/{pipeline-B30irGMD.js → pipeline-BeCc441z.js} +1 -1
  40. package/dist/{project-DSzWKU3C.js → project-B5KIO0q-.js} +9 -9
  41. package/dist/{pseudo-DNbNNVGP.js → pseudo-B2DUpoLu.js} +2 -1
  42. package/dist/{react-intl-tzGIk6G3.js → react-intl-C8JehBBL.js} +6 -6
  43. package/dist/rename-ZVGq9ZG1.js +577 -0
  44. package/dist/repeated-uuI1tUGg.js +85 -0
  45. package/dist/{restore-BG_zMpSj.js → restore-xlBIrtRt.js} +8 -8
  46. package/dist/{rewrite-hAcRJwiZ.js → rewrite-BwzXoBiA.js} +1 -1
  47. package/dist/{run-CFzR3V93.js → run-CQ9pDLSa.js} +50 -23
  48. package/dist/scan-worker.d.ts +1 -1
  49. package/dist/scan-worker.js +1 -1
  50. package/dist/{server-ceuzzkal.js → server-Br8tAuG2.js} +28 -8
  51. package/dist/{server-WlxZH0oX.js → server-DJRpUQVZ.js} +793 -12
  52. package/dist/server.d.ts +1 -1
  53. package/dist/server.js +7 -1
  54. package/dist/{sitemap-796jJKUT.js → sitemap-CSAkm6oi.js} +4 -4
  55. package/dist/{sources-DuOdM02f.js → sources-DNVbYsgs.js} +4 -3
  56. package/dist/{status-CTH3qI-0.js → status-q6M3rBrh.js} +3 -3
  57. package/dist/{sync-CpL0Qsgw.js → sync-BNIAwMhR.js} +6 -6
  58. package/dist/test.d.ts +1 -1
  59. package/dist/test.js +53 -12
  60. package/dist/{translate-BrfVRkjl.js → translate-BP4iVhOR.js} +6 -6
  61. package/dist/{types-BaG1LboH.d.ts → types-B4wNX6PA.d.ts} +4 -2
  62. package/dist/{types-Cy2bPdSg.d.ts → types-_4UdFhR9.d.ts} +10 -1
  63. package/dist/{types-Ds_vebja.js → types-xR2exI3L.js} +1 -0
  64. package/dist/{units-VVLgQ7x7.js → units-DPPfCN7j.js} +3 -3
  65. package/dist/{validate-zv4-IZyZ.js → validate-CgzaDdOY.js} +2 -2
  66. package/dist/{version-BFs370Ce.js → version-DC-J5WvV.js} +2 -2
  67. package/dist/{vite-scan-DFKSGVE9.js → vite-scan-kM8Ta3rO.js} +6 -6
  68. package/dist/vite.d.ts +1 -1
  69. package/dist/vite.js +20 -16
  70. package/dist/{vue-i18n-CBmZqHbG.js → vue-i18n-_uIXlFVh.js} +6 -6
  71. package/dist/{which-BpyJyBkX.js → which-DFWk_KwN.js} +8 -8
  72. package/dist/{worker-BjzVqJVO.js → worker-zlhNj4y3.js} +4 -4
  73. package/package.json +1 -1
  74. package/dist/i18next-1waHziMy.js +0 -1
  75. package/dist/migrate-khCY8TE0.js +0 -1
@@ -1,13 +1,16 @@
1
1
  import { a as __toCommonJS, i as __require, n as __esmMin, r as __exportAll, t as __commonJSMin } from "./rolldown-runtime-C1I3wEg2.js";
2
- import { t as VERSION } from "./version-BFs370Ce.js";
3
- import { u as toPosix } from "./validate-zv4-IZyZ.js";
4
- import { F as isIncluded, l as loadCatalogSet, s as catalogPath, u as parseCatalog } from "./library-BfSOBeBd.js";
5
- import { r as loadConfig, t as findConfigFile } from "./load-BFLLqY8x.js";
6
- import { n as isDiagnosticError } from "./diagnostics-1onDF6Ua.js";
7
- import { i as scanSource, r as scanConfig } from "./worker-BjzVqJVO.js";
8
- import { S as checkTranslation, _ as indexCatalog, b as localeView, d as projectOf, v as indexCatalogs, w as syntaxOfEntry, x as messageView } from "./project-DSzWKU3C.js";
9
- import { o as errorMessage } from "./output-CF9uvk_-.js";
10
- import { dirname, relative } from "node:path";
2
+ import { t as VERSION } from "./version-DC-J5WvV.js";
3
+ import { d as toPosix } from "./validate-CgzaDdOY.js";
4
+ import { F as isIncluded, l as loadCatalogSet, s as catalogPath, u as parseCatalog } from "./library-tp_xqzSY.js";
5
+ import { i as writesText, n as repeatedDiagnostics, r as repeatedTexts, t as quoted } from "./repeated-uuI1tUGg.js";
6
+ import { r as loadConfig, t as findConfigFile } from "./load-BSIeGJ5v.js";
7
+ import { n as isDiagnosticError } from "./diagnostics-LgIWyeSp.js";
8
+ import { s as scanProject } from "./sync-BNIAwMhR.js";
9
+ import { i as scanSource, r as scanConfig } from "./worker-zlhNj4y3.js";
10
+ import { S as checkTranslation, _ as indexCatalog, b as localeView, d as projectOf, v as indexCatalogs, w as syntaxOfEntry, x as messageView } from "./project-B5KIO0q-.js";
11
+ import { o as errorMessage } from "./output-D5tAt8q4.js";
12
+ import { dirname, posix, relative, resolve } from "node:path";
13
+ import { readFile } from "node:fs/promises";
11
14
  import { fileURLToPath, pathToFileURL } from "node:url";
12
15
  // ../../node_modules/.pnpm/vscode-languageserver-textdocument@1.0.15/node_modules/vscode-languageserver-textdocument/lib/esm/main.js
13
16
  var FullTextDocument$1 = class FullTextDocument$1 {
@@ -10745,7 +10748,7 @@ var require_api = /* @__PURE__ */ __commonJSMin(((exports, module, this$2) => {
10745
10748
  ProposedFeatures.all = { __brand: "features" };
10746
10749
  })(ProposedFeatures || (exports.ProposedFeatures = ProposedFeatures = {}));
10747
10750
  }));
10748
- // src/cli/lsp/text.ts
10751
+ // src/cli/lsp/edited.ts
10749
10752
  var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module, this$1) => {
10750
10753
  var __createBinding = this$1 && this$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
10751
10754
  if (k2 === void 0) k2 = k;
@@ -10990,6 +10993,46 @@ var import_main = (/* @__PURE__ */ __commonJSMin(((exports, module, this$1) => {
10990
10993
  };
10991
10994
  }
10992
10995
  })))();
10996
+ /** Literal call sites per id, counted once so the entries loop below stays linear. */
10997
+ function countById(list) {
10998
+ const counts = /* @__PURE__ */ new Map();
10999
+ for (const occurrence of list) counts.set(occurrence.id, (counts.get(occurrence.id) ?? 0) + 1);
11000
+ return counts;
11001
+ }
11002
+ function findEditedText(input) {
11003
+ const { file, current, saved, entries, sitesOf, threshold } = input;
11004
+ const fresh = current.filter((o) => writesText(o) && !entries.has(o.id));
11005
+ if (fresh.length === 0) return null;
11006
+ const candidates = [];
11007
+ const savedCounts = countById(saved);
11008
+ const currentCounts = countById(current);
11009
+ for (const [id, entry] of entries) {
11010
+ if (entry.manualId !== null || entry.source === null) continue;
11011
+ const used = entry.refs.includes(file) ? 1 : 0;
11012
+ const before = Math.max(savedCounts.get(id) ?? 0, used);
11013
+ const now = currentCounts.get(id) ?? 0;
11014
+ if (now >= before) continue;
11015
+ const remaining = sitesOf(id);
11016
+ if (remaining + (before - now) < threshold) continue;
11017
+ candidates.push({
11018
+ id,
11019
+ source: entry.source,
11020
+ remaining
11021
+ });
11022
+ }
11023
+ if (candidates.length === 0) return null;
11024
+ const ids = new Set(fresh.map((o) => o.id));
11025
+ const [only] = candidates;
11026
+ return {
11027
+ paired: candidates.length === 1 && ids.size === 1 && only !== void 0 ? {
11028
+ old: only,
11029
+ id: fresh[0]?.id
11030
+ } : null,
11031
+ candidates,
11032
+ sites: fresh
11033
+ };
11034
+ }
11035
+ // src/cli/lsp/text.ts
10993
11036
  const QUOTES = /* @__PURE__ */ new Set([
10994
11037
  "\"",
10995
11038
  "'",
@@ -11127,6 +11170,633 @@ function hoverMarkdown(message) {
11127
11170
  function escapeMarkdown(text) {
11128
11171
  return text.replace(/[\\`*_{}[\]<>()#+!|]/g, "\\$&");
11129
11172
  }
11173
+ // src/cli/lsp/extract.ts
11174
+ /**
11175
+ * The edit behind "Declare once with msg()": one declaration for a text
11176
+ * written at many `t()` call sites, and `t(ref)` at the sites. Pure over
11177
+ * the files' texts (the workspace reads them), so the choices are testable
11178
+ * and the rule stays one predictable sentence: **the declaration goes in the
11179
+ * file when every site is in it, else in `messages.ts` (`messages.js` for
11180
+ * JavaScript-only sites) in the nearest directory above all the sites**, and
11181
+ * every other site imports it from there.
11182
+ *
11183
+ * A site is replaced only when its literal is still where the scan saw it
11184
+ * and means the same text, so a file edited since the scan loses that one
11185
+ * site and keeps working. Component files (`.vue`, `.svelte`, `.astro`) and
11186
+ * `rich*` calls are left alone: a template cannot import the declaration,
11187
+ * and a `rich*` call's handlers belong to the call.
11188
+ */
11189
+ const SCRIPT = /\.(?:[cm]?[jt]s|[jt]sx)$/;
11190
+ const JAVASCRIPT = /\.(?:[cm]?js|jsx)$/;
11191
+ const MESSAGES = "messages";
11192
+ const VI18N = "@menapo/vi18n";
11193
+ const RESERVED = new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let msg new null package private protected public return static super switch this throw true try typeof undefined var void while with yield t".split(" "));
11194
+ /** `Sign in` → `signIn`, from the first five words; `text` when no word is left. */
11195
+ function nameOf(source) {
11196
+ const name = (source.match(/[\p{L}\p{Nd}]+/gu)?.slice(0, 5) ?? []).map((word, i) => i === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join("");
11197
+ if (name === "") return "text";
11198
+ return /^\p{Nd}/u.test(name) ? `text${name}` : name;
11199
+ }
11200
+ /** The first of `name`, `name2`, `name3`… that is no reserved word and appears in none of `texts`. */
11201
+ function freeName(name, texts) {
11202
+ const taken = (candidate) => RESERVED.has(candidate) || texts.some((text) => new RegExp(`(?<![\\p{L}\\p{N}_$])${candidate}(?![\\p{L}\\p{N}_$])`, "u").test(text));
11203
+ if (!taken(name)) return name;
11204
+ for (let n = 2;; n++) if (!taken(`${name}${n}`)) return `${name}${n}`;
11205
+ }
11206
+ /** The value of the string literal `raw` (quotes included), or null when it holds an escape this does not read or a `${`. */
11207
+ function decodeLiteral(raw) {
11208
+ const quote = raw[0];
11209
+ if (raw.length < 2 || raw.at(-1) !== quote || quote !== "\"" && quote !== "'" && quote !== "`") return null;
11210
+ const body = raw.slice(1, -1);
11211
+ if (quote === "`" && body.includes("${")) return null;
11212
+ let out = "";
11213
+ for (let i = 0; i < body.length; i++) {
11214
+ const ch = body[i];
11215
+ if (ch !== "\\") {
11216
+ out += ch;
11217
+ continue;
11218
+ }
11219
+ const next = body[++i];
11220
+ const simple = {
11221
+ n: "\n",
11222
+ t: " ",
11223
+ r: "\r",
11224
+ b: "\b",
11225
+ f: "\f",
11226
+ v: "\v",
11227
+ "0": "\0",
11228
+ "\\": "\\",
11229
+ "'": "'",
11230
+ "\"": "\"",
11231
+ "`": "`",
11232
+ "\n": ""
11233
+ };
11234
+ if (next !== void 0 && next in simple) {
11235
+ if (next === "0" && /\d/.test(body[i + 1] ?? "")) return null;
11236
+ out += simple[next];
11237
+ } else if (next === "x" && /^[\da-f]{2}$/i.test(body.slice(i + 1, i + 3))) {
11238
+ out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 3), 16));
11239
+ i += 2;
11240
+ } else if (next === "u" && /^[\da-f]{4}$/i.test(body.slice(i + 1, i + 5))) {
11241
+ out += String.fromCharCode(Number.parseInt(body.slice(i + 1, i + 5), 16));
11242
+ i += 4;
11243
+ } else return null;
11244
+ }
11245
+ return out;
11246
+ }
11247
+ /** JSON's string syntax is JavaScript's for any message text. */
11248
+ const literalOf = (text) => JSON.stringify(text);
11249
+ /** The end offset of the last top-level `import` statement, or 0 without any. */
11250
+ function importsEnd(text) {
11251
+ const statement = /^import\b(?!\s*[.(])(?:[^;"']|"[^"\n]*"|'[^'\n]*')*?(["'])[^"'\n]+\1[ \t]*;?/gm;
11252
+ let end = 0;
11253
+ for (const match of text.matchAll(statement)) end = match.index + match[0].length;
11254
+ return end;
11255
+ }
11256
+ /** The `import { … } from "<from>"` statements of `text`: where the braces open and what each names. */
11257
+ function namedImports(text, from) {
11258
+ const named = new RegExp(`import(\\s+type)?\\s*\\{([^}]*)\\}\\s*from\\s*(["'])${from.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}\\3`, "g");
11259
+ return [...text.matchAll(named)].map((match) => ({
11260
+ open: match.index + match[0].indexOf("{") + 1,
11261
+ typeOnly: match[1] !== void 0,
11262
+ specs: match[2].split(",").map((part) => /^\s*(type\s+)?([\w$]+)(?:\s+as\s+([\w$]+))?\s*$/.exec(part)).filter((found) => found !== null).map((found) => ({
11263
+ imported: found[2],
11264
+ local: found[3] ?? found[2],
11265
+ type: found[1] !== void 0
11266
+ }))
11267
+ }));
11268
+ }
11269
+ /** The local name `text` already gives to `name` imported from `from` (`msg as m` gives `m`), or null. */
11270
+ function localNameOf(text, name, from) {
11271
+ for (const statement of namedImports(text, from)) {
11272
+ if (statement.typeOnly) continue;
11273
+ const found = statement.specs.find((spec) => !spec.type && spec.imported === name);
11274
+ if (found !== void 0) return found.local;
11275
+ }
11276
+ return null;
11277
+ }
11278
+ /** An edit that makes `text` import `name` from `from`: into an existing `import { … } from` that module, else a new line after the imports. */
11279
+ function addNamedImport(text, name, from) {
11280
+ if (localNameOf(text, name, from) === name) return null;
11281
+ const statement = namedImports(text, from).find((candidate) => !candidate.typeOnly);
11282
+ if (statement !== void 0) return {
11283
+ start: statement.open,
11284
+ end: statement.open,
11285
+ newText: ` ${name},`
11286
+ };
11287
+ const end = insertionPoint(text);
11288
+ const line = `import { ${name} } from "${from}";`;
11289
+ return end === 0 ? {
11290
+ start: 0,
11291
+ end: 0,
11292
+ newText: `${line}\n\n`
11293
+ } : {
11294
+ start: end,
11295
+ end,
11296
+ newText: `\n${line}`
11297
+ };
11298
+ }
11299
+ /**
11300
+ * Where the first statement may go: after a shebang and the directives
11301
+ * (`"use client"`) that must stay first, 0 when the file has neither.
11302
+ */
11303
+ function prologueEnd(text) {
11304
+ let end = /^#![^\n]*/.exec(text)?.[0].length ?? 0;
11305
+ const directive = /(?:\s|\/\/[^\n]*|\/\*[\s\S]*?\*\/)*(["'])(?:(?!\1)[^\n\\])*\1[ \t]*;?/y;
11306
+ for (;;) {
11307
+ directive.lastIndex = end;
11308
+ if (directive.exec(text) === null) return end;
11309
+ end = directive.lastIndex;
11310
+ }
11311
+ }
11312
+ /** After the last import, else after the prologue, else 0. */
11313
+ function insertionPoint(text) {
11314
+ const end = importsEnd(text);
11315
+ return end > 0 ? end : prologueEnd(text);
11316
+ }
11317
+ /** Where the call's literal is now, when it is still a `t(…)` first argument that means `canonical`. */
11318
+ function locate(text, site, input, canonical) {
11319
+ const start = offsetOf(text, lineStarts(text), site.line, site.column);
11320
+ const end = tokenEnd(text, start);
11321
+ const value = decodeLiteral(text.slice(start, end));
11322
+ if (value === null || input.canonical(value) !== canonical) return null;
11323
+ if (!/\bt\s*\(\s*$/.test(text.slice(Math.max(0, start - 40), start))) return null;
11324
+ return {
11325
+ start,
11326
+ end,
11327
+ value
11328
+ };
11329
+ }
11330
+ /** Where the declaration goes for sites in `files`: the file itself, else a messages module above all of them. */
11331
+ function declarationFile(files) {
11332
+ if (files.length === 1) return files[0];
11333
+ const dirs = files.map((file) => posix.dirname(file).split("/").filter((part) => part !== "."));
11334
+ let common = dirs[0];
11335
+ for (const dir of dirs) {
11336
+ let n = 0;
11337
+ while (n < common.length && n < dir.length && common[n] === dir[n]) n++;
11338
+ common = common.slice(0, n);
11339
+ }
11340
+ const extension = files.every((file) => JAVASCRIPT.test(file)) ? "js" : "ts";
11341
+ return posix.join(...common, `${MESSAGES}.${extension}`);
11342
+ }
11343
+ /** The relative import specifier from `file` to `target`, without extension. */
11344
+ function specifier(file, target) {
11345
+ const relative = posix.relative(posix.join("/", posix.dirname(file)), posix.join("/", target.replace(/\.[cm]?[jt]s$/, "")));
11346
+ return relative.startsWith(".") ? relative : `./${relative}`;
11347
+ }
11348
+ /** The sites still plain `t("…")` calls of the text, with the files' texts as read. */
11349
+ function replaceable(input, canonical) {
11350
+ const texts = /* @__PURE__ */ new Map();
11351
+ const found = [];
11352
+ let source = null;
11353
+ for (const site of input.text.sites) {
11354
+ if (site.callee !== "t" || site.annotated || !SCRIPT.test(site.file) || site.line === 0) continue;
11355
+ const content = texts.get(site.file) ?? input.read(site.file);
11356
+ if (content === null) continue;
11357
+ texts.set(site.file, content);
11358
+ const where = locate(content, site, input, canonical);
11359
+ if (where === null) continue;
11360
+ source ??= where.value;
11361
+ found.push({
11362
+ file: site.file,
11363
+ start: where.start,
11364
+ end: where.end
11365
+ });
11366
+ }
11367
+ return source === null || found.length === 0 ? null : {
11368
+ found,
11369
+ texts,
11370
+ source
11371
+ };
11372
+ }
11373
+ /** The edit that declares `name` in a file that exists: after its imports when it holds every site, else at its end. */
11374
+ function declareIn(content, name, source, local) {
11375
+ const alias = localNameOf(content, "msg", VI18N);
11376
+ const declaration = `const ${name} = ${alias ?? "msg"}(${literalOf(source)});`;
11377
+ const importMsg = alias === null ? addNamedImport(content, "msg", VI18N) : null;
11378
+ if (!local) {
11379
+ const tail = content === "" || content.endsWith("\n") ? "" : "\n";
11380
+ const end = content.length;
11381
+ const edits = [{
11382
+ start: end,
11383
+ end,
11384
+ newText: `${tail}\nexport ${declaration}\n`
11385
+ }];
11386
+ return importMsg === null ? edits : [...edits, importMsg];
11387
+ }
11388
+ const end = insertionPoint(content);
11389
+ const joined = importMsg !== null && importMsg.start === end;
11390
+ const gap = /^\r?\n\r?\n/.test(content.slice(end)) || end >= content.length ? "" : "\n";
11391
+ const edit = {
11392
+ start: end,
11393
+ end,
11394
+ newText: `${joined ? importMsg.newText : ""}\n\n${declaration}${gap}`
11395
+ };
11396
+ return importMsg === null || joined ? [edit] : [edit, importMsg];
11397
+ }
11398
+ /** `\n` in an inserted text becomes the file's own line break, so a CRLF file stays CRLF. */
11399
+ function inEolOf(content, edit) {
11400
+ if (content === null || !content.includes("\r\n")) return edit;
11401
+ return {
11402
+ ...edit,
11403
+ newText: edit.newText.replace(/\r?\n/g, "\r\n")
11404
+ };
11405
+ }
11406
+ /** Outside the config root (or on another drive): the fix never writes there. */
11407
+ function outsideRoot(file) {
11408
+ return /^(?:\.\.(?:\/|$)|\/|[A-Za-z]:)/.test(file);
11409
+ }
11410
+ /**
11411
+ * The plan for one repeated text, or null when nothing can be replaced
11412
+ * correctly: no site is still a plain `t("…")` in a script file, or the
11413
+ * messages module would sit where the scan does not read.
11414
+ */
11415
+ function planExtraction(input) {
11416
+ const canonical = input.canonical(input.text.source);
11417
+ if (input.text.sites.some((site) => outsideRoot(site.file))) return null;
11418
+ const sites = canonical === null ? null : replaceable(input, canonical);
11419
+ if (sites === null) return null;
11420
+ const { found, texts, source } = sites;
11421
+ const everywhere = new Set(input.text.sites.map((site) => site.file));
11422
+ const declaredIn = declarationFile([...everywhere]);
11423
+ if (!input.included(declaredIn)) return null;
11424
+ const existing = texts.get(declaredIn) ?? input.read(declaredIn);
11425
+ const name = freeName(nameOf(source), [...texts.values(), existing ?? ""]);
11426
+ const edits = /* @__PURE__ */ new Map();
11427
+ const add = (file, list) => {
11428
+ const content = texts.get(file) ?? (file === declaredIn ? existing : null);
11429
+ const kept = list.filter((edit) => edit !== null);
11430
+ edits.set(file, [...edits.get(file) ?? [], ...kept.map((edit) => inEolOf(content, edit))]);
11431
+ };
11432
+ for (const site of found) add(site.file, [{
11433
+ start: site.start,
11434
+ end: site.end,
11435
+ newText: name
11436
+ }]);
11437
+ if (existing === null) add(declaredIn, [{
11438
+ start: 0,
11439
+ end: 0,
11440
+ newText: `import { msg } from "${VI18N}";\n\nexport const ${name} = msg(${literalOf(source)});\n`
11441
+ }]);
11442
+ else add(declaredIn, declareIn(existing, name, source, everywhere.size === 1));
11443
+ for (const file of new Set(found.map((site) => site.file))) {
11444
+ if (file === declaredIn) continue;
11445
+ add(file, [addNamedImport(texts.get(file), name, specifier(file, declaredIn))]);
11446
+ }
11447
+ return {
11448
+ name,
11449
+ declaredIn,
11450
+ create: existing === null,
11451
+ edits,
11452
+ replaced: found.length
11453
+ };
11454
+ }
11455
+ // src/cli/lsp/text-checks.ts
11456
+ /**
11457
+ * The two project-wide text checks of the editor and their quick fixes:
11458
+ *
11459
+ * - **repeated text** (`extract-repeated-text`, warning): one literal at
11460
+ * `extraction.repeatedText` call sites or more; the fix declares it once
11461
+ * with `msg()` (`extract.ts`);
11462
+ * - **edited text** (`extract-edited-text`, information): a text many sites
11463
+ * share was edited at one of them (`edited.ts` has the heuristic); the fix
11464
+ * hands the rename the old and new text, and "Keep as a new text" marks
11465
+ * the site `vi18n-ignore`, the comment the rest of the tooling already
11466
+ * reads.
11467
+ *
11468
+ * `repeatedText: false` turns both off.
11469
+ */
11470
+ const REPLACE_COMMAND = "vi18n.replaceText";
11471
+ function plural(n) {
11472
+ return n === 1 ? "place" : "places";
11473
+ }
11474
+ async function textDiagnostics(state, doc) {
11475
+ const threshold = state.project.config.extraction.repeatedText;
11476
+ if (threshold === false) return [];
11477
+ await state.sites.ready();
11478
+ const starts = lineStarts(doc.text);
11479
+ const out = [];
11480
+ for (const text of state.sites.repeated(threshold)) {
11481
+ const first = text.sites[0];
11482
+ for (const diagnostic of repeatedDiagnostics([text])) {
11483
+ if (diagnostic.file !== doc.refFile || diagnostic.line === void 0) continue;
11484
+ const entry = {
11485
+ range: tokenRange(doc.text, starts, diagnostic.line, diagnostic.column ?? 1),
11486
+ severity: 2,
11487
+ code: diagnostic.code,
11488
+ source: "vi18n",
11489
+ message: diagnostic.message,
11490
+ data: {
11491
+ kind: "repeated",
11492
+ id: text.id
11493
+ }
11494
+ };
11495
+ if (first !== void 0 && first.line > 0) entry.relatedInformation = [{
11496
+ location: {
11497
+ uri: pathToFileURL(resolve(state.project.config.root, first.file)).href,
11498
+ range: {
11499
+ start: {
11500
+ line: first.line - 1,
11501
+ character: first.column - 1
11502
+ },
11503
+ end: {
11504
+ line: first.line - 1,
11505
+ character: first.column - 1
11506
+ }
11507
+ }
11508
+ },
11509
+ message: `first of the ${text.sites.length} sites`
11510
+ }];
11511
+ out.push(entry);
11512
+ }
11513
+ }
11514
+ const edited = editedIn(state, doc, threshold);
11515
+ if (edited !== null) out.push(...editedDiagnostics(edited, doc, starts));
11516
+ return out;
11517
+ }
11518
+ function editedIn(state, doc, threshold) {
11519
+ const entries = state.indexes.get(state.project.config.sourceLocale)?.entries;
11520
+ if (entries === void 0) return null;
11521
+ return findEditedText({
11522
+ file: doc.refFile,
11523
+ current: doc.occurrences,
11524
+ saved: state.sites.saved(doc.refFile),
11525
+ entries,
11526
+ sitesOf: (id) => state.sites.sitesOf(id),
11527
+ threshold
11528
+ });
11529
+ }
11530
+ function editedDiagnostics(edited, doc, starts) {
11531
+ const { paired, candidates } = edited;
11532
+ const out = [];
11533
+ for (const site of edited.sites) {
11534
+ if (site.line === 0) continue;
11535
+ let message;
11536
+ let data;
11537
+ if (paired !== null) {
11538
+ const { old } = paired;
11539
+ message = `This text was ${quoted(old.source)} in ${old.remaining} other ${plural(old.remaining)}; they still use the old text`;
11540
+ data = {
11541
+ kind: "edited",
11542
+ id: site.id,
11543
+ from: old.source,
11544
+ to: site.source,
11545
+ others: old.remaining
11546
+ };
11547
+ } else {
11548
+ message = `A text used in several places was edited in this file: ${candidates.slice(0, 3).map((c) => `${quoted(c.source)} (${c.remaining} ${plural(c.remaining)})`).join(", ")}${candidates.length > 3 ? ", …" : ""}; several texts changed here, so change the other places too, or keep this as a new text`;
11549
+ data = {
11550
+ kind: "edited-hint",
11551
+ id: site.id
11552
+ };
11553
+ }
11554
+ out.push({
11555
+ range: tokenRange(doc.text, starts, site.line, site.column),
11556
+ severity: 3,
11557
+ code: "extract-edited-text",
11558
+ source: "vi18n",
11559
+ message,
11560
+ data
11561
+ });
11562
+ }
11563
+ return out;
11564
+ }
11565
+ async function textActions(context, diagnostics) {
11566
+ const out = [];
11567
+ for (const diagnostic of diagnostics) {
11568
+ const data = diagnostic.data;
11569
+ if (diagnostic.source !== "vi18n" || data === void 0) continue;
11570
+ if (data.kind === "repeated") {
11571
+ const action = await extractAction(context, diagnostic, data.id);
11572
+ if (action !== null) out.push(action);
11573
+ continue;
11574
+ }
11575
+ if (data.kind === "edited") {
11576
+ const title = `Replace ${quoted(data.from)} with ${quoted(data.to)} in all ${data.others} other ${plural(data.others)}`;
11577
+ out.push({
11578
+ title,
11579
+ kind: "quickfix",
11580
+ diagnostics: [diagnostic],
11581
+ isPreferred: true,
11582
+ command: {
11583
+ title,
11584
+ command: REPLACE_COMMAND,
11585
+ arguments: [{
11586
+ uri: context.doc.uri,
11587
+ from: data.from,
11588
+ to: data.to
11589
+ }]
11590
+ }
11591
+ });
11592
+ }
11593
+ if (data.kind === "edited" || data.kind === "edited-hint") out.push(keepAction(context.doc, diagnostic, data.id));
11594
+ }
11595
+ return out;
11596
+ }
11597
+ /** `/* vi18n-ignore *\/` before each literal of the new text in this document: the edit stays a new message. */
11598
+ function keepAction(doc, diagnostic, id) {
11599
+ const starts = lineStarts(doc.text);
11600
+ const edits = [];
11601
+ for (const occurrence of doc.occurrences) {
11602
+ if (occurrence.id !== id || !writesText(occurrence) || occurrence.line === 0) continue;
11603
+ const at = lspPosition(starts, offsetOf(doc.text, starts, occurrence.line, occurrence.column));
11604
+ edits.push({
11605
+ range: {
11606
+ start: at,
11607
+ end: at
11608
+ },
11609
+ newText: "/* vi18n-ignore -- a new text */ "
11610
+ });
11611
+ }
11612
+ return {
11613
+ title: "Keep as a new text",
11614
+ kind: "quickfix",
11615
+ diagnostics: [diagnostic],
11616
+ edit: { changes: { [doc.uri]: edits } }
11617
+ };
11618
+ }
11619
+ async function extractAction({ state, doc, files }, diagnostic, id) {
11620
+ const threshold = state.project.config.extraction.repeatedText;
11621
+ if (threshold === false) return null;
11622
+ const text = state.sites.repeated(threshold).find((candidate) => candidate.id === id);
11623
+ if (text === void 0) return null;
11624
+ const { config, codec } = state.project;
11625
+ const sites = [...new Set(text.sites.map((site) => site.file))];
11626
+ const contents = /* @__PURE__ */ new Map();
11627
+ for (const file of [...sites, declarationFile(sites)]) {
11628
+ if (contents.has(file)) continue;
11629
+ contents.set(file, file === doc.refFile ? doc.text : await files.text(resolve(config.root, file)));
11630
+ }
11631
+ const plan = planExtraction({
11632
+ text,
11633
+ read: (file) => contents.get(file) ?? null,
11634
+ included: (file) => isIncluded(resolve(config.root, file), config),
11635
+ canonical: (source) => {
11636
+ try {
11637
+ return codec.canonicalize(source);
11638
+ } catch {
11639
+ return null;
11640
+ }
11641
+ }
11642
+ });
11643
+ if (plan === null) return null;
11644
+ const changes = [];
11645
+ const ordered = [...plan.edits].sort(([a], [b]) => Number(b === plan.declaredIn) - Number(a === plan.declaredIn));
11646
+ for (const [file, edits] of ordered) {
11647
+ const path = resolve(config.root, file);
11648
+ const uri = file === doc.refFile ? doc.uri : pathToFileURL(path).href;
11649
+ const before = contents.get(file) ?? "";
11650
+ if (plan.create && file === plan.declaredIn) changes.push({
11651
+ kind: "create",
11652
+ uri,
11653
+ options: { ignoreIfExists: true }
11654
+ });
11655
+ changes.push({
11656
+ textDocument: {
11657
+ uri,
11658
+ version: files.version(path)
11659
+ },
11660
+ edits: toLsp$1(before, edits)
11661
+ });
11662
+ }
11663
+ return {
11664
+ title: `Declare once with msg() as ${plan.name} (${plan.replaced} sites)`,
11665
+ kind: "quickfix",
11666
+ diagnostics: [diagnostic],
11667
+ edit: { documentChanges: changes }
11668
+ };
11669
+ }
11670
+ function toLsp$1(text, edits) {
11671
+ const starts = lineStarts(text);
11672
+ return edits.map((edit) => ({
11673
+ range: {
11674
+ start: lspPosition(starts, edit.start),
11675
+ end: lspPosition(starts, edit.end)
11676
+ },
11677
+ newText: edit.newText
11678
+ }));
11679
+ }
11680
+ // src/cli/lsp/sites.ts
11681
+ /**
11682
+ * Every literal call site in the project, for the checks that compare
11683
+ * documents with each other (repeated and edited texts). The disk scan comes
11684
+ * first and is cached like `extract`'s; an open document's own scan replaces
11685
+ * its file's, so unsaved text counts. A change the server cannot see (a file
11686
+ * saved elsewhere, an `extract` run) marks the disk scan stale, and the next
11687
+ * answer reads it again, which the scan cache makes cheap.
11688
+ */
11689
+ var ProjectSites = class {
11690
+ load;
11691
+ disk = null;
11692
+ loading = null;
11693
+ open = /* @__PURE__ */ new Map();
11694
+ diskRevision = 0;
11695
+ /** Bumped by every change to the open files; keys what is derived from them. */
11696
+ openRevision = 0;
11697
+ /** Bumped only when a file opens or closes: the disk's share of the totals changes then, not per keystroke. */
11698
+ openFiles = 0;
11699
+ writers = null;
11700
+ /** The disk scan without the open files' own, by id; rebuilt when the disk scan or the set of open files changes, never per keystroke. */
11701
+ base = null;
11702
+ constructor(load) {
11703
+ this.load = load;
11704
+ }
11705
+ /** Waits for the disk scan; reads it again when something marked it stale. */
11706
+ async ready() {
11707
+ if (this.disk !== null) return;
11708
+ this.loading ??= this.load().then((map) => {
11709
+ this.disk = map;
11710
+ }).finally(() => {
11711
+ this.loading = null;
11712
+ this.diskRevision++;
11713
+ });
11714
+ await this.loading;
11715
+ }
11716
+ /** The disk scan no longer matches the files. */
11717
+ invalidate() {
11718
+ this.disk = null;
11719
+ this.diskRevision++;
11720
+ }
11721
+ /** An open document's occurrences as its text is now. */
11722
+ setOpen(file, occurrences) {
11723
+ if (!this.open.has(file)) this.openFiles++;
11724
+ this.open.set(file, occurrences);
11725
+ this.openRevision++;
11726
+ }
11727
+ dropOpen(file) {
11728
+ if (!this.open.delete(file)) return;
11729
+ this.openFiles++;
11730
+ this.openRevision++;
11731
+ }
11732
+ /** A file's occurrences as of its last save (the disk scan), for the edit's "before". */
11733
+ saved(file) {
11734
+ return this.disk?.get(file) ?? [];
11735
+ }
11736
+ /**
11737
+ * The disk's literal call sites by id, without the open files'. Per
11738
+ * keystroke only the open files' own occurrences are read again, so a
11739
+ * large project costs the same as a small one.
11740
+ */
11741
+ diskBase(threshold) {
11742
+ let base = this.base;
11743
+ if (base?.diskRevision !== this.diskRevision || base.openFiles !== this.openFiles) {
11744
+ const byId = /* @__PURE__ */ new Map();
11745
+ for (const [file, list] of this.disk ?? []) {
11746
+ if (this.open.has(file)) continue;
11747
+ for (const occurrence of list) {
11748
+ if (!writesText(occurrence)) continue;
11749
+ const sites = byId.get(occurrence.id);
11750
+ if (sites === void 0) byId.set(occurrence.id, [occurrence]);
11751
+ else sites.push(occurrence);
11752
+ }
11753
+ }
11754
+ base = {
11755
+ diskRevision: this.diskRevision,
11756
+ openFiles: this.openFiles,
11757
+ byId,
11758
+ frequent: /* @__PURE__ */ new Map()
11759
+ };
11760
+ this.base = base;
11761
+ }
11762
+ if (!base.frequent.has(threshold)) {
11763
+ const ids = [];
11764
+ for (const [id, sites] of base.byId) if (sites.length >= threshold) ids.push(id);
11765
+ base.frequent.set(threshold, ids);
11766
+ }
11767
+ return base;
11768
+ }
11769
+ openWriters() {
11770
+ if (this.writers?.revision === this.openRevision) return this.writers.byId;
11771
+ const byId = /* @__PURE__ */ new Map();
11772
+ for (const list of this.open.values()) for (const occurrence of list) {
11773
+ if (!writesText(occurrence)) continue;
11774
+ const sites = byId.get(occurrence.id);
11775
+ if (sites === void 0) byId.set(occurrence.id, [occurrence]);
11776
+ else sites.push(occurrence);
11777
+ }
11778
+ this.writers = {
11779
+ revision: this.openRevision,
11780
+ byId
11781
+ };
11782
+ return byId;
11783
+ }
11784
+ /** Literal call sites of one id, in the project as it is now. */
11785
+ sitesOf(id) {
11786
+ return (this.diskBase(Number.POSITIVE_INFINITY).byId.get(id)?.length ?? 0) + (this.openWriters().get(id)?.length ?? 0);
11787
+ }
11788
+ repeated(threshold) {
11789
+ const { byId, frequent } = this.diskBase(threshold);
11790
+ const opened = this.openWriters();
11791
+ const ids = /* @__PURE__ */ new Set([...frequent.get(threshold) ?? [], ...opened.keys()]);
11792
+ const all = [];
11793
+ for (const id of ids) {
11794
+ for (const occurrence of byId.get(id) ?? []) all.push(occurrence);
11795
+ for (const occurrence of opened.get(id) ?? []) all.push(occurrence);
11796
+ }
11797
+ return repeatedTexts(all, threshold);
11798
+ }
11799
+ };
11130
11800
  // src/cli/lsp/workspace.ts
11131
11801
  /**
11132
11802
  * What the language server knows (INTERNALS §2.17): per `vi18n.config.ts`,
@@ -11159,6 +11829,11 @@ var LanguageWorkspace = class {
11159
11829
  this.documents.delete(uri);
11160
11830
  const state = this.states.get(uri);
11161
11831
  this.states.delete(uri);
11832
+ if (state?.kind === "code") {
11833
+ const closed = await this.projects.get(state.configFile);
11834
+ closed?.sites.dropOpen(state.refFile);
11835
+ closed?.sites.invalidate();
11836
+ }
11162
11837
  if (state?.kind !== "catalog") return false;
11163
11838
  const project = await this.projects.get(state.configFile);
11164
11839
  if (project == null) return false;
@@ -11229,11 +11904,14 @@ var LanguageWorkspace = class {
11229
11904
  range: tokenRange(document.text, starts, occurrence.line, occurrence.column)
11230
11905
  });
11231
11906
  }
11907
+ project.sites.setOpen(refFile, result.occurrences);
11232
11908
  this.states.set(uri, {
11233
11909
  kind: "code",
11234
11910
  version: document.version,
11235
11911
  configFile,
11912
+ refFile,
11236
11913
  located,
11914
+ occurrences: result.occurrences,
11237
11915
  diagnostics: result.diagnostics.filter((diagnostic) => diagnostic.file === void 0 || diagnostic.file === refFile),
11238
11916
  text: document.text
11239
11917
  });
@@ -11262,8 +11940,67 @@ var LanguageWorkspace = class {
11262
11940
  out.push(toLsp(diagnostic, range));
11263
11941
  }
11264
11942
  for (const { occurrence, range } of state.located) out.push(...this.translationDiagnostics(project, occurrence, range));
11943
+ out.push(...await textDiagnostics(project, this.checked(uri, state)));
11265
11944
  return out;
11266
11945
  }
11946
+ /** Quick fixes for the repeated and edited text diagnostics of a document. */
11947
+ async codeActions(uri, diagnostics) {
11948
+ await this.refresh(uri);
11949
+ const state = this.states.get(uri);
11950
+ if (state?.kind !== "code") return [];
11951
+ const project = await this.projects.get(state.configFile);
11952
+ if (project == null) return [];
11953
+ return textActions({
11954
+ state: project,
11955
+ doc: this.checked(uri, state),
11956
+ files: {
11957
+ text: (path) => this.textOf(path),
11958
+ version: (path) => this.versionOf(path)
11959
+ }
11960
+ }, diagnostics);
11961
+ }
11962
+ /**
11963
+ * "Replace in all places": the rename changes the old text to the edited
11964
+ * one in every file but this document, which already says it. Returns the
11965
+ * rewritten sites; open documents' diagnostics change afterwards.
11966
+ */
11967
+ async replaceText(request) {
11968
+ const path = filePath(request.uri);
11969
+ const project = path === null ? null : await this.projectFor(path);
11970
+ if (path === null || project === null) throw new Error(`${request.uri} belongs to no vi18n project`);
11971
+ const { renameMessage } = await import("./rename-ZVGq9ZG1.js");
11972
+ const { sites } = await renameMessage(project.project, {
11973
+ from: request.from,
11974
+ to: request.to,
11975
+ review: false,
11976
+ merge: false,
11977
+ skip: [path]
11978
+ }, { write: true });
11979
+ project.sites.invalidate();
11980
+ for (const locale of project.project.config.locales) await this.reloadLocale(project, locale);
11981
+ return sites.length;
11982
+ }
11983
+ checked(uri, state) {
11984
+ return {
11985
+ uri,
11986
+ refFile: state.refFile,
11987
+ text: state.text,
11988
+ occurrences: state.occurrences
11989
+ };
11990
+ }
11991
+ /** An open buffer's text, else the file on disk; null when it does not exist. */
11992
+ async textOf(path) {
11993
+ for (const document of this.documents.values()) if (filePath(document.uri) === path) return document.text;
11994
+ try {
11995
+ return await readFile(path, "utf8");
11996
+ } catch {
11997
+ return null;
11998
+ }
11999
+ }
12000
+ versionOf(path) {
12001
+ for (const document of this.documents.values()) if (filePath(document.uri) === path) return document.version;
12002
+ return null;
12003
+ }
11267
12004
  async hover(uri, position) {
11268
12005
  const found = await this.occurrenceAt(uri, position);
11269
12006
  if (found === null) return null;
@@ -11324,6 +12061,7 @@ var LanguageWorkspace = class {
11324
12061
  const locale = project?.catalogs.get(path);
11325
12062
  if (project == null || locale === void 0 || project.overlays.has(locale)) continue;
11326
12063
  await this.reloadLocale(project, locale);
12064
+ project.sites.invalidate();
11327
12065
  changed = true;
11328
12066
  }
11329
12067
  }
@@ -11386,7 +12124,8 @@ var LanguageWorkspace = class {
11386
12124
  scan: scanConfig(config),
11387
12125
  catalogs: new Map(config.locales.map((locale) => [catalogPath(config, locale), locale])),
11388
12126
  indexes: /* @__PURE__ */ new Map(),
11389
- overlays: /* @__PURE__ */ new Set()
12127
+ overlays: /* @__PURE__ */ new Set(),
12128
+ sites: new ProjectSites(() => this.scanSites(config, project.codec))
11390
12129
  };
11391
12130
  const loaded = await loadCatalogSet(config, project.codec);
11392
12131
  for (const diagnostic of loaded.diagnostics) if (diagnostic.severity === "error") this.options.log(`vi18n: ${diagnostic.message}`);
@@ -11394,6 +12133,18 @@ var LanguageWorkspace = class {
11394
12133
  this.options.log(`vi18n: loaded ${configFile} (${config.locales.join(", ")})`);
11395
12134
  return state;
11396
12135
  }
12136
+ /** The disk scan of every literal call site (the scan cache makes a repeat cheap); nothing when the checks are off. */
12137
+ async scanSites(config, codec) {
12138
+ const sites = /* @__PURE__ */ new Map();
12139
+ if (config.extraction.repeatedText === false) return sites;
12140
+ try {
12141
+ const scanned = await scanProject(config, codec, { cache: true });
12142
+ for (const file of scanned.files) sites.set(file.refFile, file.occurrences);
12143
+ } catch (error) {
12144
+ this.options.log(`vi18n: scanning the project failed: ${errorMessage(error)}`);
12145
+ }
12146
+ return sites;
12147
+ }
11397
12148
  async reloadLocale(project, locale) {
11398
12149
  const { config, codec } = project.project;
11399
12150
  const read = (await loadCatalogSet(config, codec, [locale])).set.get(locale);
@@ -11680,7 +12431,9 @@ var LanguageServer = class {
11680
12431
  change: import_main.TextDocumentSyncKind.Incremental
11681
12432
  },
11682
12433
  hoverProvider: true,
11683
- definitionProvider: true
12434
+ definitionProvider: true,
12435
+ codeActionProvider: { codeActionKinds: ["quickfix"] },
12436
+ executeCommandProvider: { commands: [REPLACE_COMMAND] }
11684
12437
  },
11685
12438
  serverInfo: {
11686
12439
  name: "vi18n",
@@ -11753,6 +12506,29 @@ var LanguageServer = class {
11753
12506
  workspace.filesChanged(changes.map((change) => change.uri)).then((changed) => changed ? this.publishAll() : void 0).catch((error) => this.log(`vi18n: ${String(error)}`));
11754
12507
  });
11755
12508
  }
12509
+ /** `vi18n.replaceText`: the rename, then every open document's diagnostics again. */
12510
+ async execute(params) {
12511
+ if (params.command !== "vi18n.replaceText") return null;
12512
+ const [request] = params.arguments ?? [];
12513
+ const { uri, from, to } = request ?? {};
12514
+ if (typeof uri !== "string" || typeof from !== "string" || typeof to !== "string") throw new Error(`${REPLACE_COMMAND} needs { uri, from, to }`);
12515
+ try {
12516
+ const sites = await this.workspace.replaceText({
12517
+ uri,
12518
+ from,
12519
+ to
12520
+ });
12521
+ this.log(`vi18n: replaced ${sites} sites`);
12522
+ } catch (error) {
12523
+ const message = error instanceof Error ? error.message : String(error);
12524
+ this.connection.sendNotification(import_main.ShowMessageNotification.type, {
12525
+ type: import_main.MessageType.Error,
12526
+ message: `vi18n: replacing the text failed: ${message}`
12527
+ });
12528
+ }
12529
+ await this.publishAll();
12530
+ return null;
12531
+ }
11756
12532
  registerRequests() {
11757
12533
  const { connection, workspace } = this;
11758
12534
  connection.onRequest(import_main.HoverRequest.type, async ({ textDocument, position }) => {
@@ -11763,6 +12539,11 @@ var LanguageServer = class {
11763
12539
  await this.settle(textDocument.uri);
11764
12540
  return workspace.definition(textDocument.uri, position);
11765
12541
  });
12542
+ connection.onRequest(import_main.CodeActionRequest.type, async ({ textDocument, context }) => {
12543
+ await this.settle(textDocument.uri);
12544
+ return workspace.codeActions(textDocument.uri, context.diagnostics);
12545
+ });
12546
+ connection.onRequest(import_main.ExecuteCommandRequest.type, (params) => this.execute(params));
11766
12547
  }
11767
12548
  };
11768
12549
  export { startLanguageServer };