locale-ai 0.6.17 → 0.6.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,7 +28,7 @@ Download 577 MB? (Y/n)
28
28
 
29
29
  ## What it handles
30
30
 
31
- - **Layouts**: `locales/en/*.json` (nested folders too) → `locales/fr/...`, or `messages/en.json` → `messages/fr.json`. `.json`, `.yaml`, `.yml`, `.po`/`.pot` (gettext), `.arb` (Flutter) and `.strings` (Apple) are all supported, mixed freely in the same project. Common folders (`locales`, `src/locales`, `public/locales`, `src/i18n`, `messages`, `lang`, `config/locales` (Rails), ...) are found automatically, or pass `--input`. Framework-specific naming is also recognized: `flutter gen-l10n`'s `app_en.arb`/`app_fr.arb` filename prefix, and Apple's `en.lproj`/`fr.lproj` directory-suffix convention (`--input en.lproj` or just the project root both work), on both the source and the generated target side.
31
+ - **Layouts**: `locales/en/*.json` (nested folders too) → `locales/fr/...`, or `messages/en.json` → `messages/fr.json`. `.json`, `.yaml`, `.yml`, `.po`/`.pot` (gettext), `.arb` (Flutter), `.strings` (Apple) and `.properties` (Java) are all supported, mixed freely in the same project. Common folders (`locales`, `src/locales`, `public/locales`, `src/i18n`, `messages`, `lang`, `config/locales` (Rails), ...) are found automatically, or pass `--input`. Framework-specific naming is also recognized: `flutter gen-l10n`'s `app_en.arb`/`app_fr.arb` filename prefix, Apple's `en.lproj`/`fr.lproj` directory-suffix convention (`--input en.lproj` or just the project root both work), and Java `ResourceBundle`'s `messages_en.properties`/`messages_fr.properties` filename prefix (region-qualified as `messages_pt_BR.properties`, with an underscore — Java's own convention, not this project's usual BCP-47 hyphen), on both the source and the generated target side.
32
32
  - **Android**: `res/values/strings.xml` → `res/values-fr/strings.xml` (or `values-pt-rBR` for a region). `<string>`, `<string-array>` and `<plurals>` are all translated; `translatable="false"` strings and `<!-- ... -->` comments are kept as-is. Resource-qualifier scripts/variants (`values-b+sr+Latn`) aren't supported — only a plain language or language-region qualifier.
33
33
  - **Apple `.xcstrings`** (Xcode 15+'s String Catalog, replacing `.strings`): every locale lives inside this one file, so point `--input` straight at it (e.g. `--input Localizable.xcstrings`; it isn't auto-detected, since a project can have several). `shouldTranslate: false` entries, and Xcode's per-device variants (`variations.iphone`/`.ipad`) or multi-variable strings (`substitutions`), are left untouched rather than mistranslated — only a single cardinal plural (`variations.plural`) is supported. A key with no explicit source-language text falls back to the key itself, matching Xcode's own convention.
34
34
  - **Placeholders are never translated or lost**: `{name}`, `{{count}}`, `%s`, `%1$s`, `%(name)s`, `%{name}`, `${name}`, `:attribute`, `$t(key)`, `@:key`, `<b>…</b>`, `<0>…</0>`, `&nbsp;`, URLs, e-mails.
@@ -37,7 +37,7 @@ Download 577 MB? (Y/n)
37
37
  - **Incremental, and edit-aware**: only missing or changed keys are translated; untouched translations are kept, so re-runs are no-ops. A small `locale-ai.lock.json` (commit it, like a package lock) remembers a hash of each source string and of the output last written for it per target locale — so editing a source string gets it re-translated automatically (it isn't enough for the target to already hold *some* text), while editing a target string by hand is detected and reported for review instead of being silently overwritten on the next run. `--overwrite` bypasses the lock and re-translates everything.
38
38
  - **Structure**: key order, numbers, booleans, arrays, indentation and trailing newline are preserved.
39
39
 
40
- **Format notes**: for `.yaml`/`.yml`, `#` comments (a translator note, an inline `# ...` after a value) survive a translation run — the target file is edited in place rather than rebuilt from scratch, so an existing comment's own value is updated without disturbing the comment, and a brand-new key is appended with no comment of its own. A newly added plural-category key (see above) is likewise appended rather than inserted between existing ones, so its position in the file won't always match the canonical `zero`/`one`/`two`/`few`/`many`/`other` order. For `.po`/`.pot`, `msgid` is the stable key (never changed) and `msgstr` is the translated value, as gettext expects — the English source's `msgstr` holds the source text when it's filled in (most generators do), and falls back to `msgid` itself when it's empty, which is normal for a `.pot` template or a project that just keeps the English text in `msgid`. That fallback only ever applies to the source file: an empty `msgstr` in an *existing target* still means "not translated yet", never "same as msgid". `msgid_plural`/`msgstr[n]` plural entries are translated too (the singular and plural source forms), then expanded to however many `msgstr[n]` the target language's plural rules need (6 for Arabic, 1 for Japanese, ...) — not full grammatical inflection for in-between categories (`few`/`many`/...), which get the plural-sourced translation verbatim, the same simplification `addPluralForms` makes for i18next. `Plural-Forms` in the header is computed for the target language, not copied from the source; an existing target file's header, and any entry's own comments (a translator's note, a hand-added `#, fuzzy`), are otherwise left exactly as last edited instead of being regenerated from the source on every rerun. `--fuzzy` flags every entry a run actually (re)translated with gettext's standard `#, fuzzy` "needs review" marker, merging onto an existing `#,` line rather than adding a second one. A `.pot` source always writes a `.po` target, never a `.pot`. For `.arb`, `@key` metadata and `@@locale` are never translated; `@@locale` is set to the target locale on output. For `.strings`, a file saved as UTF-16 (Xcode's traditional default) is read like a UTF-8 one, an unquoted key (`title = "Settings";`, without quotes around `title`) is read the same as a quoted one, and `\U00e9`-style escapes are decoded — output is always written as UTF-8 with quoted keys, regardless of how the source was saved. For Android `strings.xml`, `translatable="false"` strings and each element's own `<!-- ... -->` comment are kept on first write, but — unlike YAML/`.po`/`.strings` — a rerun regenerates the file from scratch rather than editing an existing target in place, so a hand-edited comment in an already-translated file won't survive a rerun. For `.xcstrings`, every target locale is written into the same one catalog file (each locale's run re-reads it first, so several locales share it safely in one invocation); an entry's `state` (e.g. a translator's `needs_review` flag) is only touched when the value it's attached to actually changes, so hand review survives a rerun.
40
+ **Format notes**: for `.yaml`/`.yml`, `#` comments (a translator note, an inline `# ...` after a value) survive a translation run — the target file is edited in place rather than rebuilt from scratch, so an existing comment's own value is updated without disturbing the comment, and a brand-new key is appended with no comment of its own. A newly added plural-category key (see above) is likewise appended rather than inserted between existing ones, so its position in the file won't always match the canonical `zero`/`one`/`two`/`few`/`many`/`other` order. For `.po`/`.pot`, `msgid` is the stable key (never changed) and `msgstr` is the translated value, as gettext expects — the English source's `msgstr` holds the source text when it's filled in (most generators do), and falls back to `msgid` itself when it's empty, which is normal for a `.pot` template or a project that just keeps the English text in `msgid`. That fallback only ever applies to the source file: an empty `msgstr` in an *existing target* still means "not translated yet", never "same as msgid". `msgid_plural`/`msgstr[n]` plural entries are translated too (the singular and plural source forms), then expanded to however many `msgstr[n]` the target language's plural rules need (6 for Arabic, 1 for Japanese, ...) — not full grammatical inflection for in-between categories (`few`/`many`/...), which get the plural-sourced translation verbatim, the same simplification `addPluralForms` makes for i18next. `Plural-Forms` in the header is computed for the target language, not copied from the source; an existing target file's header, and any entry's own comments (a translator's note, a hand-added `#, fuzzy`), are otherwise left exactly as last edited instead of being regenerated from the source on every rerun. `--fuzzy` flags every entry a run actually (re)translated with gettext's standard `#, fuzzy` "needs review" marker, merging onto an existing `#,` line rather than adding a second one. A `.pot` source always writes a `.po` target, never a `.pot`. For `.arb`, `@key` metadata and `@@locale` are never translated; `@@locale` is set to the target locale on output. For `.strings`, a file saved as UTF-16 (Xcode's traditional default) is read like a UTF-8 one, an unquoted key (`title = "Settings";`, without quotes around `title`) is read the same as a quoted one, and `\U00e9`-style escapes are decoded — output is always written as UTF-8 with quoted keys, regardless of how the source was saved. For Android `strings.xml`, `translatable="false"` strings and each element's own `<!-- ... -->` comment are kept on first write, but — unlike YAML/`.po`/`.strings` — a rerun regenerates the file from scratch rather than editing an existing target in place, so a hand-edited comment in an already-translated file won't survive a rerun. For `.xcstrings`, every target locale is written into the same one catalog file (each locale's run re-reads it first, so several locales share it safely in one invocation); an entry's `state` (e.g. a translator's `needs_review` flag) is only touched when the value it's attached to actually changes, so hand review survives a rerun. For `.properties`, `#`/`!` comments and blank lines survive a rerun exactly like YAML's — the target file is edited in place rather than rebuilt from scratch; a `\`-continued multi-line value is read correctly but gets collapsed onto one line if it's ever actually rewritten (an untouched one keeps its original layout), and a line with no unescaped `=`/`:` at all is left completely alone rather than guessed at. `.properties` has no plural convention of its own, so ICU `{count, plural, ...}` inside a value is handled the same generic way it is everywhere else.
41
41
 
42
42
  ## Why locale-ai?
43
43
 
package/dist/locales.js CHANGED
@@ -2,7 +2,14 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { Document, isMap, isScalar, parseDocument } from "yaml";
4
4
  import { parseLocale } from "./lang.js";
5
- const EXTENSIONS = [".json", ".yaml", ".yml", ".po", ".pot", ".arb", ".strings"];
5
+ const EXTENSIONS = [".json", ".yaml", ".yml", ".po", ".pot", ".arb", ".strings", ".properties"];
6
+ /**
7
+ * Java's `ResourceBundle` convention names a region-qualified `.properties` file
8
+ * "fr_FR", not this project's BCP-47 "fr-FR" everywhere else — so the tag is
9
+ * underscore-joined only at the filename boundary, for this one extension.
10
+ */
11
+ const propertiesTag = (ext, tag) => (ext === ".properties" ? tag.replace("-", "_") : tag);
12
+ const tagFromPropertiesQualifier = (ext, qualifier) => (ext === ".properties" ? qualifier.replace("_", "-") : qualifier);
6
13
  const CANDIDATES = [
7
14
  "locales",
8
15
  "src/locales",
@@ -45,11 +52,12 @@ const isDir = (p) => fs.existsSync(p) && fs.statSync(p).isDirectory();
45
52
  const isFile = (p) => fs.existsSync(p) && fs.statSync(p).isFile();
46
53
  /** The source-locale file's extension, if `<root>/<from><ext>` exists for one of EXTENSIONS. */
47
54
  function fileExtAt(root, from) {
48
- return EXTENSIONS.find((ext) => isFile(path.join(root, `${from}${ext}`)));
55
+ return EXTENSIONS.find((ext) => isFile(path.join(root, `${propertiesTag(ext, from)}${ext}`)));
49
56
  }
50
57
  /**
51
58
  * A prefixed source-locale file, if `<root>/<prefix>_<from><ext>` exists for one of
52
- * EXTENSIONS — the convention `flutter gen-l10n` uses by default ("app_en.arb").
59
+ * EXTENSIONS — the convention `flutter gen-l10n` uses by default ("app_en.arb"), and
60
+ * also how a Java `ResourceBundle` basename ("messages_en.properties") is found.
53
61
  */
54
62
  function prefixedFileAt(root, from) {
55
63
  if (!isDir(root))
@@ -58,7 +66,7 @@ function prefixedFileAt(root, from) {
58
66
  if (!isFile(path.join(root, entry)))
59
67
  continue;
60
68
  for (const ext of EXTENSIONS) {
61
- const suffix = `_${from}${ext}`;
69
+ const suffix = `_${propertiesTag(ext, from)}${ext}`;
62
70
  if (entry.endsWith(suffix) && entry.length > suffix.length) {
63
71
  return { ext, prefix: entry.slice(0, -suffix.length) };
64
72
  }
@@ -89,7 +97,7 @@ function layoutAt(root, from) {
89
97
  return undefined;
90
98
  }
91
99
  const dirNameFor = (layout, tag) => `${tag}${layout.dirSuffix ?? ""}`;
92
- const fileNameFor = (layout, tag, ext) => `${layout.prefix ? `${layout.prefix}_` : ""}${tag}${ext}`;
100
+ const fileNameFor = (layout, tag, ext) => `${layout.prefix ? `${layout.prefix}_` : ""}${propertiesTag(ext, tag)}${ext}`;
93
101
  export function detectLayout(cwd, from, input) {
94
102
  if (input) {
95
103
  const abs = path.resolve(cwd, input);
@@ -117,12 +125,15 @@ export function detectLayout(cwd, from, input) {
117
125
  return { kind: "xcstrings", root: path.dirname(abs), file: abs };
118
126
  }
119
127
  const base = path.basename(abs);
120
- const directExt = EXTENSIONS.find((ext) => base === `${from}${ext}`);
128
+ const directExt = EXTENSIONS.find((ext) => base === `${propertiesTag(ext, from)}${ext}`);
121
129
  if (directExt && isFile(abs))
122
130
  return { kind: "file", root: path.dirname(abs), ext: directExt };
123
- const prefixedExt = EXTENSIONS.find((ext) => base.endsWith(`_${from}${ext}`) && base.length > `_${from}${ext}`.length);
131
+ const prefixedExt = EXTENSIONS.find((ext) => {
132
+ const suffix = `_${propertiesTag(ext, from)}${ext}`;
133
+ return base.endsWith(suffix) && base.length > suffix.length;
134
+ });
124
135
  if (prefixedExt && isFile(abs)) {
125
- const suffix = `_${from}${prefixedExt}`;
136
+ const suffix = `_${propertiesTag(prefixedExt, from)}${prefixedExt}`;
126
137
  return { kind: "file", root: path.dirname(abs), ext: prefixedExt, prefix: base.slice(0, -suffix.length) };
127
138
  }
128
139
  const l = layoutAt(abs, from);
@@ -216,9 +227,9 @@ export function existingTargets(layout, from) {
216
227
  const prefix = layout.prefix ? `${layout.prefix}_` : "";
217
228
  return fs
218
229
  .readdirSync(layout.root)
219
- .filter((f) => f.startsWith(prefix) && f.endsWith(ext) && f.slice(prefix.length, -ext.length) !== from)
220
- .map((f) => f.slice(prefix.length, -ext.length))
221
- .filter(looksLikeLocale)
230
+ .filter((f) => f.startsWith(prefix) && f.endsWith(ext))
231
+ .map((f) => tagFromPropertiesQualifier(ext, f.slice(prefix.length, -ext.length)))
232
+ .filter((tag) => tag !== from && looksLikeLocale(tag))
222
233
  .sort();
223
234
  }
224
235
  const suffix = layout.dirSuffix ?? "";
@@ -367,6 +378,109 @@ function readStringsDoc(file, text) {
367
378
  };
368
379
  return { data, serialize };
369
380
  }
381
+ /** Java `.properties`: `\n`, `\t`, `\r`, `\f`, `\\` and `\uXXXX` escapes, plus an escaped separator/leading-space. */
382
+ function unescapeProperties(s) {
383
+ return s.replace(/\\(u[0-9a-fA-F]{4}|.)/gs, (_m, esc) => {
384
+ if (esc[0] === "u" && esc.length === 5)
385
+ return String.fromCharCode(parseInt(esc.slice(1), 16));
386
+ return { n: "\n", t: "\t", r: "\r", f: "\f" }[esc] ?? esc;
387
+ });
388
+ }
389
+ function escapeProperties(s) {
390
+ let out = s.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");
391
+ if (out[0] === " ")
392
+ out = `\\${out}`;
393
+ return out;
394
+ }
395
+ /** True when `s` ends in an odd run of backslashes — Java's line-continuation rule. */
396
+ const endsWithContinuation = (s) => (/\\*$/.exec(s)[0].length % 2 === 1);
397
+ /** Splits `key<ws>?[=:]<ws>?value` at the first unescaped `=`/`:`, skipping `\X` pairs. Undefined if there's none (a key-only or malformed line). */
398
+ function splitPropertyLine(line) {
399
+ let i = 0;
400
+ while (i < line.length) {
401
+ const c = line[i];
402
+ if (c === "\\") {
403
+ i += 2;
404
+ continue;
405
+ }
406
+ if (c === "=" || c === ":") {
407
+ const key = unescapeProperties(line.slice(0, i).trimEnd());
408
+ let v = i + 1;
409
+ while (v < line.length && (line[v] === " " || line[v] === "\t"))
410
+ v++;
411
+ return { key, valueStart: v };
412
+ }
413
+ i++;
414
+ }
415
+ return undefined;
416
+ }
417
+ /** Parses `.properties` text into passthrough lines (comments, blank lines, unparsable lines) and key/value entries. */
418
+ function parsePropertiesBlocks(text) {
419
+ const physical = text.split(/\r?\n/);
420
+ const blocks = [];
421
+ const data = newObj();
422
+ let i = 0;
423
+ while (i < physical.length) {
424
+ const line = physical[i];
425
+ const trimmedStart = line.replace(/^[ \t\f]+/, "");
426
+ if (trimmedStart === "" || trimmedStart[0] === "#" || trimmedStart[0] === "!") {
427
+ blocks.push({ text: line });
428
+ i++;
429
+ continue;
430
+ }
431
+ const split = splitPropertyLine(line);
432
+ if (!split) {
433
+ blocks.push({ text: line });
434
+ i++;
435
+ continue;
436
+ }
437
+ let valueRaw = line.slice(split.valueStart);
438
+ while (endsWithContinuation(valueRaw) && i + 1 < physical.length) {
439
+ valueRaw = valueRaw.slice(0, -1) + physical[++i].replace(/^[ \t\f]+/, "");
440
+ }
441
+ data[split.key] = unescapeProperties(valueRaw);
442
+ blocks.push({ key: split.key, prefix: line.slice(0, split.valueStart) });
443
+ i++;
444
+ }
445
+ return { blocks, data };
446
+ }
447
+ /**
448
+ * Java `ResourceBundle` `.properties`: a flat `key=value` (or `key: value`) list, one
449
+ * per line, `#`/`!` line comments, `\`-continued multi-line values, and `\uXXXX`/`\n`/
450
+ * `\t` escapes. There's no plural or array convention of its own — a value containing
451
+ * ICU `{count, plural, ...}` syntax is still handled generically by the ICU extractor
452
+ * elsewhere, same as any other format.
453
+ *
454
+ * Unlike Android/ARB/`.xcstrings` (which regenerate the whole file from the source's
455
+ * own structure every run), this edits an existing target file's lines in place, the
456
+ * same as YAML/`.po`: untouched entries, comments and blank lines keep their exact
457
+ * text and position, and a value that didn't change is never rewritten. A multi-line
458
+ * (`\`-continued) value is always collapsed to one line when it's rewritten, though —
459
+ * only an *unchanged* continued value keeps its original multi-line layout. A line
460
+ * with no unescaped `=`/`:` at all (so not a recognizable `key=value` pair) is passed
461
+ * through untouched rather than guessed at.
462
+ */
463
+ function readPropertiesDoc(file, text) {
464
+ const { blocks, data } = parsePropertiesBlocks(text);
465
+ const serialize = (d, _targetTag, existingText) => {
466
+ const obj = isObj(d) ? d : newObj();
467
+ const baseBlocks = existingText !== undefined ? parsePropertiesBlocks(existingText).blocks : blocks;
468
+ const seen = new Set();
469
+ const lines = baseBlocks.map((b) => {
470
+ if (!("key" in b))
471
+ return b.text;
472
+ seen.add(b.key);
473
+ return `${b.prefix}${escapeProperties(typeof obj[b.key] === "string" ? obj[b.key] : "")}`;
474
+ });
475
+ for (const k of Object.keys(obj)) {
476
+ if (seen.has(k) || typeof obj[k] !== "string")
477
+ continue;
478
+ lines.push(`${k}=${escapeProperties(obj[k])}`);
479
+ }
480
+ return lines.join("\n");
481
+ };
482
+ return { data, serialize };
483
+ }
370
484
  /** Android's `&entity;` plus its own backslash escapes (`\'`, `\"`, `\n`, `\t`) and `<![CDATA[...]]>`. */
371
485
  function unescapeAndroidXml(s) {
372
486
  return s
@@ -906,6 +1020,8 @@ export function readLocaleDoc(file, tag, isSource = false, fuzzy = false) {
906
1020
  return readArbDoc(file, text);
907
1021
  if (ext === ".strings")
908
1022
  return readStringsDoc(file, text);
1023
+ if (ext === ".properties")
1024
+ return readPropertiesDoc(file, text);
909
1025
  if (ext === ".xml")
910
1026
  return readAndroidXmlDoc(file, text);
911
1027
  if (ext === ".xcstrings")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "locale-ai",
3
- "version": "0.6.17",
3
+ "version": "0.6.18",
4
4
  "description": "Translate your i18n locale files locally on CPU. Free, offline, no API keys.",
5
5
  "author": "Taha KHABOUSS",
6
6
  "repository": {