@ultimat3/cli 31.51.0 → 31.52.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 (65) hide show
  1. package/README.md +9 -9
  2. package/package.json +29 -29
  3. package/src/catalog-layout.ts +194 -0
  4. package/src/cmd-i18n-spec.ts +4 -4
  5. package/src/cmd-i18n-split.ts +133 -0
  6. package/src/cmd-i18n.ts +46 -66
  7. package/src/config-redact.ts +20 -4
  8. package/src/db-rollback-pass.ts +4 -1
  9. package/src/dev-child-watch.ts +16 -0
  10. package/src/dev-db-migrate.ts +27 -46
  11. package/src/dev-db-migrator-hold.ts +131 -0
  12. package/src/dev-db-rollback.ts +11 -2
  13. package/src/dev-rebuild-schema.ts +7 -24
  14. package/src/generate-catalog-locales.ts +25 -2
  15. package/src/generate-follow-ups.ts +8 -3
  16. package/src/i18n-audit.ts +17 -33
  17. package/src/i18n-index.ts +108 -31
  18. package/src/i18n-locale-parity.ts +14 -6
  19. package/src/i18n-new-locale.ts +75 -0
  20. package/src/i18n-registration.ts +52 -27
  21. package/src/island-capture.ts +36 -7
  22. package/src/merge-state.ts +3 -2
  23. package/src/messages-floor.ts +2 -0
  24. package/src/messages.ts +2 -0
  25. package/src/serve-boot-telemetry.ts +106 -0
  26. package/src/serve-boot.ts +23 -4
  27. package/src/shot-blank.ts +70 -0
  28. package/src/templates/catalog-barrel.ts +84 -0
  29. package/src/templates/guard-released-forms.ts +2 -1
  30. package/src/templates/guard-untranslated-string.ts +27 -6
  31. package/src/templates/locales.ts +6 -0
  32. package/src/templates/scaffold-gitattributes.ts +9 -2
  33. package/src/templates/scaffold-i18n.ts +10 -6
  34. package/src/templates/shapes/offline.ts +5 -2
  35. package/src/test-ignores.ts +3 -2
  36. package/src/verify-floor.ts +9 -1
  37. package/src/verify-local-only.ts +66 -0
  38. package/src/verify-run.ts +17 -2
  39. package/wiki/Actions.md +1 -1
  40. package/wiki/Auth.md +3 -3
  41. package/wiki/Batching-And-Preloading.md +1 -0
  42. package/wiki/CLI-Reference-Data.md +241 -0
  43. package/wiki/CLI-Reference-Gate.md +572 -0
  44. package/wiki/CLI-Reference-Project.md +414 -0
  45. package/wiki/CLI-Reference-Ship.md +348 -0
  46. package/wiki/CLI-Reference-Tools.md +666 -0
  47. package/wiki/CLI-Reference.md +14 -2225
  48. package/wiki/Compared.md +8 -8
  49. package/wiki/Configuration.md +26 -2
  50. package/wiki/Deployment.md +1 -1
  51. package/wiki/Entities-And-Migrations.md +3 -2
  52. package/wiki/I18n.md +39 -5
  53. package/wiki/Installation.md +1 -1
  54. package/wiki/Jobs-And-Workflows.md +29 -1
  55. package/wiki/Known-Gaps.md +3 -0
  56. package/wiki/Observability.md +15 -1
  57. package/wiki/Outbound-HTTP.md +62 -2
  58. package/wiki/PWA-And-Offline.md +1 -1
  59. package/wiki/Policies-And-Authz.md +10 -0
  60. package/wiki/Realtime.md +29 -2
  61. package/wiki/Static-Assets.md +1 -1
  62. package/wiki/Testing.md +33 -0
  63. package/wiki/Theming.md +31 -8
  64. package/wiki/Troubleshooting.md +1 -1
  65. package/wiki/Upgrading.md +5 -1
@@ -4,13 +4,16 @@
4
4
  // with `x i18n add <locale>`, the one command that starts a catalog holding every existing key.
5
5
 
6
6
  import { renderFixShellArg } from '@ultimat3/core';
7
- import { type Catalog, loadCatalog } from '@ultimat3/i18n';
7
+ import { type Catalog, loadCatalog, partitionCatalog } from '@ultimat3/i18n';
8
8
  import { loadAppCatalogs } from '@ultimat3/i18n/app-catalogs';
9
+ import type { CatalogLayout } from './catalog-layout';
10
+ import { readCatalogLayout } from './catalog-layout';
9
11
  import { BadFlagError } from './errors';
10
12
  import { resolveDefaultLocale, seedCatalog, serializeCatalog } from './i18n-audit';
11
13
  import { catalogLocales } from './i18n-index';
12
14
  import type { GeneratedFile } from './templates';
13
15
  import { CATALOG_ROOT, catalogPath } from './templates';
16
+ import { catalogDir } from './templates/locales';
14
17
 
15
18
  /** The locale a `merge: 'json'` file is the catalog of, or `undefined` for any other file. */
16
19
  const localeOf = (file: GeneratedFile): string | undefined => {
@@ -69,13 +72,33 @@ export async function localiseCatalogs(
69
72
  });
70
73
  }
71
74
  }
72
- return files.map((file) => {
75
+ const localised = files.map((file) => {
73
76
  const locale = localeOf(file);
74
77
  if (file.merge !== 'json' || locale === undefined || locale === fallback) return file;
75
78
  if (fallback === undefined) return file;
76
79
  const generated: unknown = JSON.parse(file.contents);
77
80
  return { ...file, contents: serializeCatalog(seedCatalog(loadCatalog(generated))) };
78
81
  });
82
+ const layout = await readCatalogLayout(root);
83
+ return localised.flatMap((file) => intoLayout(file, layout));
84
+ }
85
+
86
+ /**
87
+ * A template's `catalogs/<locale>.json` landed where the app keeps that locale: as is for a flat
88
+ * one, and for a split one as one `merge: 'json'` file per namespace — each key in the existing
89
+ * file of its longest prefix, else in its namespace's own, created. Written as `<locale>.json`
90
+ * beside the directory, it would be `X_CATALOG_LAYOUT_MIXED` on the next read.
91
+ */
92
+ function intoLayout(file: GeneratedFile, layout: CatalogLayout): readonly GeneratedFile[] {
93
+ const locale = localeOf(file);
94
+ const entry = locale === undefined ? undefined : layout[locale];
95
+ if (file.merge !== 'json' || locale === undefined || entry?.form !== 'split') return [file];
96
+ const parts = partitionCatalog(loadCatalog(JSON.parse(file.contents)), entry.files);
97
+ return [...parts].map(([name, part]) => ({
98
+ ...file,
99
+ path: `${catalogDir(locale)}/${name}`,
100
+ contents: serializeCatalog(part),
101
+ }));
79
102
  }
80
103
 
81
104
  /**
@@ -26,11 +26,16 @@ export interface FollowUps {
26
26
  readonly findings: readonly Finding[];
27
27
  }
28
28
 
29
- /** The locale each written catalog file is for: a dry run's catalogs are not on the disk yet. */
29
+ /**
30
+ * The locale each written catalog file is for: a dry run's catalogs are not on the disk yet. A
31
+ * flat `<locale>.json`, or any namespace file under a split locale's `<locale>/`.
32
+ */
30
33
  const writtenLocales = (written: readonly string[]): readonly string[] =>
31
34
  written.flatMap((path) => {
32
35
  const stem = path.startsWith(`${CATALOG_ROOT}/`) ? path.slice(CATALOG_ROOT.length + 1) : '';
33
- return stem.endsWith('.json') && !stem.includes('/') ? [stem.slice(0, -'.json'.length)] : [];
36
+ if (!stem.endsWith('.json')) return [];
37
+ const slash = stem.indexOf('/');
38
+ return [slash === -1 ? stem.slice(0, -'.json'.length) : stem.slice(0, slash)];
34
39
  });
35
40
 
36
41
  export async function followUpEdits(
@@ -55,7 +60,7 @@ export async function followUpEdits(
55
60
  // A catalog on disk and a locale the app can select are two facts — see `syncI18nIndex`.
56
61
  const indexSync =
57
62
  written.length > 0
58
- ? await syncI18nIndex(root, disk, writtenLocales(written))
63
+ ? await syncI18nIndex(root, disk, [...new Set(writtenLocales(written))], written)
59
64
  : { registered: true, findings: [] };
60
65
  return {
61
66
  edited: [
package/src/i18n-audit.ts CHANGED
@@ -3,27 +3,26 @@
3
3
  // testable without a ParsedArgs or a rendered message.
4
4
 
5
5
  // why: `node:` and not Bun: `Bun.file().exists()` answers false for a directory, and `existsSync`
6
- // is how a missing `catalogs/` directory reads as "nothing shipped" instead of a throw; Bun has no
6
+ // is how a missing `packages/i18n` reads as "no catalog module" instead of a throw; Bun has no
7
7
  // path API at all — `join` builds the absolute path `Bun.file` reads; `posixRelative` turns it
8
8
  // back into the root-relative POSIX shape every CLI-reported path is keyed by.
9
9
  import { existsSync } from 'node:fs';
10
10
  import { join } from 'node:path';
11
- import { DEFAULT_LOCALE, renderThrowable } from '@ultimat3/core';
11
+ import { DEFAULT_LOCALE } from '@ultimat3/core';
12
12
  import type { Catalog, Extraction, ExtractReport, Locale } from '@ultimat3/i18n';
13
13
  import {
14
14
  auditCatalogs,
15
- catalogInvalid,
16
15
  catalogKeys,
17
16
  extractFromFiles,
18
- loadCatalog,
19
17
  missingFrom,
20
18
  nestCatalog,
21
19
  } from '@ultimat3/i18n';
20
+ import type { CatalogLayout } from './catalog-layout';
21
+ import { loadLayoutCatalogs, readCatalogLayout } from './catalog-layout';
22
22
  import { APP_KEY_SHAPES } from './i18n-app-key-shapes';
23
23
  import { isLoudMiss, loudMiss } from './i18n-registration';
24
24
  import { posixRelative } from './posix-path';
25
25
  import { eachSourceFile, isTest } from './source-files';
26
- import { CATALOG_ROOT, catalogPath } from './templates/locales';
27
26
 
28
27
  /**
29
28
  * Every key the app's own source names: a `t()` call, a mail block or subject, a push payload
@@ -54,35 +53,13 @@ export async function scanSource(root: string): Promise<Extraction> {
54
53
  }
55
54
 
56
55
  /**
57
- * A `JSON.parse` failure is still a catalog problem, not a bare-Error crash through this command —
58
- * reported through the same factory a structural violation (`loadCatalog` below) uses.
59
- */
60
- function parseCatalogJson(path: string, raw: string): unknown {
61
- try {
62
- return JSON.parse(raw);
63
- } catch (error) {
64
- throw catalogInvalid(path, renderThrowable(error));
65
- }
66
- }
67
-
68
- /**
69
- * Every `packages/i18n/catalogs/*.json` on disk, parsed and flattened through `loadCatalog` —
70
- * never a bare `JSON.parse`: a nested `{ one, other }` plural authored by hand is a known past
71
- * bug, and `loadCatalog` is the seam that fails it loud (`X_CATALOG_INVALID`) instead of auditing
72
- * it as an empty catalog. No `catalogs/` directory yet (a fresh app, or `packages/i18n` never
73
- * scaffolded) yields `{}` — every caller here treats that as "nothing shipped", not an error.
56
+ * Every catalog on disk, parsed and flattened, flat `catalogs/<locale>.json` and split
57
+ * `catalogs/<locale>/` alike (`catalog-layout.ts`). No `catalogs/` directory yet (a fresh app, or
58
+ * `packages/i18n` never scaffolded) yields `{}` — every caller here treats that as "nothing
59
+ * shipped", not an error.
74
60
  */
75
61
  export async function loadCatalogs(root: string): Promise<Readonly<Record<Locale, Catalog>>> {
76
- const dir = join(root, CATALOG_ROOT);
77
- if (!existsSync(dir)) return {};
78
- const catalogs: Record<string, Catalog> = {};
79
- for await (const entry of new Bun.Glob('*.json').scan({ cwd: dir, absolute: false })) {
80
- const locale = entry.replace(/\.json$/, '');
81
- const path = catalogPath(locale);
82
- const raw = await Bun.file(join(root, path)).text();
83
- catalogs[locale] = loadCatalog(parseCatalogJson(path, raw));
84
- }
85
- return catalogs;
62
+ return loadLayoutCatalogs(root, await readCatalogLayout(root));
86
63
  }
87
64
 
88
65
  export interface AuditFacts {
@@ -93,6 +70,8 @@ export interface AuditFacts {
93
70
  readonly extraction: Extraction;
94
71
  /** The `prefix*` patterns derived from dynamic calls, carried for the same reason. */
95
72
  readonly ignoreUnused: readonly string[];
73
+ /** Each locale's form on disk, so a finding names the file or directory the keys live in. */
74
+ readonly layout: CatalogLayout;
96
75
  }
97
76
 
98
77
  /** The static head of a template literal, up to its first interpolation. */
@@ -117,7 +96,11 @@ export function runtimeKeyPatterns(extraction: Extraction): readonly string[] {
117
96
 
118
97
  /** The source scan and the catalogs on disk, audited together — the one fact `x i18n check` reports. */
119
98
  export async function auditApp(root: string): Promise<AuditFacts> {
120
- const [extraction, catalogs] = await Promise.all([scanSource(root), loadCatalogs(root)]);
99
+ const layout = await readCatalogLayout(root);
100
+ const [extraction, catalogs] = await Promise.all([
101
+ scanSource(root),
102
+ loadLayoutCatalogs(root, layout),
103
+ ]);
121
104
  const ignoreUnused = runtimeKeyPatterns(extraction);
122
105
  return {
123
106
  // `reference` is what sees a key no static shape names: `t(\`plans.\${x}\`)` reads the same
@@ -126,6 +109,7 @@ export async function auditApp(root: string): Promise<AuditFacts> {
126
109
  catalogs,
127
110
  extraction,
128
111
  ignoreUnused,
112
+ layout,
129
113
  };
130
114
  }
131
115
 
package/src/i18n-index.ts CHANGED
@@ -1,4 +1,5 @@
1
- // The one writer of `packages/i18n/src/index.ts`, shared by `x g` and `x i18n add|sync`.
1
+ // The one writer of `packages/i18n/src/index.ts` and of each split locale's barrel
2
+ // (`catalogs/<locale>/index.ts`), shared by `x g` and `x i18n add|sync|split`.
2
3
  //
3
4
  // A catalog file existing on disk and the app being able to SELECT that locale are two different
4
5
  // facts, and only this closes the gap: the index hardcodes `locales: { en }`, so a locale whose
@@ -6,26 +7,20 @@
6
7
  // (`X_CATALOG_UNREGISTERED`). `x i18n add fr` wrote the file, touched nothing else, and left
7
8
  // `x verify` red with a fix line that named an edit nobody could perform (#F4).
8
9
 
9
- // why: Bun has no synchronous existence check — `Bun.file(p).exists()` is async, and this decides
10
- // whether to write at all, before any await the caller could interleave with.
11
- import { existsSync } from 'node:fs';
12
10
  import { stripComments } from '@ultimat3/core';
13
11
  import { APP_CATALOGS_PATH } from '@ultimat3/i18n/app-catalogs';
12
+ import type { CatalogLayout, LocaleLayout } from './catalog-layout';
13
+ import { readCatalogLayout } from './catalog-layout';
14
14
  import type { GenerateDisk } from './generate-disk';
15
15
  import { appDisk } from './generate-disk';
16
- import { containedPath } from './generate-write';
17
16
  import type { Finding } from './output';
18
17
  import { CATALOG_ROOT, i18nIndex, localeEntry, localeImport } from './templates';
18
+ import { catalogBarrel } from './templates/catalog-barrel';
19
+ import { CATALOG_BARREL, catalogDir } from './templates/locales';
19
20
 
20
- /** Every locale with a catalog on disk, sorted — the file names are the tags. */
21
+ /** Every locale with a catalog on disk, sorted — flat file stems and split directories alike. */
21
22
  export async function catalogLocales(root: string): Promise<readonly string[]> {
22
- const catalogDir = containedPath(root, CATALOG_ROOT);
23
- if (!existsSync(catalogDir)) return [];
24
- const locales: string[] = [];
25
- for await (const entry of new Bun.Glob('*.json').scan({ cwd: catalogDir, absolute: false })) {
26
- locales.push(entry.replace(/\.json$/, ''));
27
- }
28
- return locales.sort();
23
+ return Object.keys(await readCatalogLayout(root));
29
24
  }
30
25
 
31
26
  /** What a sync did: whether every catalog on disk is now selectable, and why not when it is not. */
@@ -37,12 +32,79 @@ export interface IndexSync {
37
32
  readonly edited?: readonly string[];
38
33
  }
39
34
 
40
- const CATALOG_IMPORT = /^import (\w+) from '\.\.\/catalogs\/([^']+)\.json';$/gm;
35
+ /** Both spellings `localeImport` writes: `import en from '../catalogs/en.json'` (flat) and
36
+ * `import { catalog as en } from '../catalogs/en'` (a split locale's barrel). */
37
+ const CATALOG_IMPORT =
38
+ /^import (?:(\w+)|\{ catalog as (\w+) \}) from '\.\.\/catalogs\/([^'/]+?)(\.json)?';$/gm;
41
39
  const LOCALES_OBJECT = /(locales:\s*\{)([^{}]*)(\})/;
42
40
 
43
- /** The tags the index imports a catalog for, in file order. */
44
- const importedLocales = (source: string): readonly string[] =>
45
- [...source.matchAll(CATALOG_IMPORT)].map((match) => match[2] ?? '');
41
+ interface ImportedLocale {
42
+ readonly locale: string;
43
+ readonly split: boolean;
44
+ readonly line: string;
45
+ readonly binding: string;
46
+ }
47
+
48
+ /** The tags the index imports a catalog for, in file order, each with the form it imports. */
49
+ const importedLocales = (source: string): readonly ImportedLocale[] =>
50
+ [...source.matchAll(CATALOG_IMPORT)].map((match) => ({
51
+ locale: match[3] ?? '',
52
+ split: match[4] === undefined,
53
+ line: match[0],
54
+ binding: match[1] ?? match[2] ?? '',
55
+ }));
56
+
57
+ /**
58
+ * Every import whose form no longer matches the disk, rewritten in place under its own binding —
59
+ * `x i18n split` turned `en.json` into `en/`, and nothing else in the index has to move.
60
+ */
61
+ function withForms(source: string, split: readonly string[]): string {
62
+ let next = source;
63
+ for (const imported of importedLocales(source)) {
64
+ const wanted = split.includes(imported.locale);
65
+ if (wanted === imported.split) continue;
66
+ const line = wanted
67
+ ? `import { catalog as ${imported.binding} } from '../catalogs/${imported.locale}';`
68
+ : `import ${imported.binding} from '../catalogs/${imported.locale}.json';`;
69
+ next = next.replace(imported.line, line);
70
+ }
71
+ return next;
72
+ }
73
+
74
+ /** Each split locale's barrel, re-derived from its files (and the ones a dry run plans). */
75
+ async function syncBarrels(
76
+ layout: CatalogLayout,
77
+ disk: GenerateDisk,
78
+ plannedFiles: readonly string[],
79
+ ): Promise<readonly string[]> {
80
+ const edited: string[] = [];
81
+ for (const [locale, { form, files }] of Object.entries(layout)) {
82
+ if (form !== 'split') continue;
83
+ const prefix = `${catalogDir(locale)}/`;
84
+ const planned = plannedFiles
85
+ .filter((path) => path.startsWith(prefix) && path.endsWith('.json'))
86
+ .map((path) => path.slice(prefix.length));
87
+ const barrel = catalogBarrel([...files, ...planned]);
88
+ const path = `${prefix}${CATALOG_BARREL}`;
89
+ if ((await disk.read(path)) === barrel) continue;
90
+ await disk.write(path, barrel);
91
+ edited.push(path);
92
+ }
93
+ return edited;
94
+ }
95
+
96
+ /** The layout on disk, with the split locales a dry run's planned files would create. */
97
+ function plannedLayout(layout: CatalogLayout, plannedFiles: readonly string[]): CatalogLayout {
98
+ const next: Record<string, LocaleLayout> = { ...layout };
99
+ for (const path of plannedFiles) {
100
+ const stem = path.startsWith(`${CATALOG_ROOT}/`) ? path.slice(CATALOG_ROOT.length + 1) : '';
101
+ const slash = stem.indexOf('/');
102
+ if (slash <= 0 || !stem.endsWith('.json')) continue;
103
+ const locale = stem.slice(0, slash);
104
+ next[locale] ??= { form: 'split', files: [] };
105
+ }
106
+ return next;
107
+ }
46
108
 
47
109
  /**
48
110
  * Makes every catalog on disk selectable, and touches the index no more than that takes.
@@ -58,26 +120,41 @@ export async function syncI18nIndex(
58
120
  disk: GenerateDisk = appDisk(root),
59
121
  /** Locales whose catalog a dry run PLANS: on the real disk only once the run has written. */
60
122
  planned: readonly string[] = [],
123
+ /** Catalog files a dry run plans, so a split locale's barrel names a namespace not yet written. */
124
+ plannedFiles: readonly string[] = [],
61
125
  ): Promise<IndexSync> {
126
+ const layout = plannedLayout(await readCatalogLayout(root), plannedFiles);
127
+ const barrels = await syncBarrels(layout, disk, plannedFiles);
128
+ const touching = (paths: readonly string[]) => (paths.length > 0 ? { edited: paths } : {});
62
129
  const current = await disk.read(APP_CATALOGS_PATH);
63
- if (current === undefined) return { registered: false, findings: [] };
64
- const onDisk = [...new Set([...(await catalogLocales(root)), ...planned])].sort();
130
+ if (current === undefined) return { registered: false, findings: [], ...touching(barrels) };
131
+ const onDisk = [...new Set([...Object.keys(layout), ...planned])].sort();
132
+ const split = onDisk.filter((locale) => layout[locale]?.form === 'split');
65
133
  const imported = importedLocales(current);
66
134
  const write = async (next: string): Promise<IndexSync> => {
67
- if (next === current) return { registered: true, findings: [] };
68
- await disk.write(APP_CATALOGS_PATH, next);
69
- return { registered: true, findings: [], edited: [APP_CATALOGS_PATH] };
135
+ const touched = next === current ? barrels : [...barrels, APP_CATALOGS_PATH];
136
+ if (next !== current) await disk.write(APP_CATALOGS_PATH, next);
137
+ return { registered: true, findings: [], ...touching(touched) };
70
138
  };
71
- if (current === i18nIndex(imported)) return write(i18nIndex(onDisk));
72
- const missing = onDisk.filter((locale) => !imported.includes(locale));
73
- if (missing.length === 0) return { registered: true, findings: [] };
74
- const edited = withLocales(current, missing);
75
- if (edited === undefined) return { registered: false, findings: [refusal(missing)] };
139
+ const importedTags = imported.map((entry) => entry.locale);
140
+ const importedSplit = imported.filter((entry) => entry.split).map((entry) => entry.locale);
141
+ if (current === i18nIndex(importedTags, importedSplit)) return write(i18nIndex(onDisk, split));
142
+ const reformed = withForms(current, split);
143
+ const missing = onDisk.filter((locale) => !importedTags.includes(locale));
144
+ if (missing.length === 0) return write(reformed);
145
+ const edited = withLocales(reformed, missing, split);
146
+ if (edited === undefined) {
147
+ return { registered: false, findings: [refusal(missing, split)], ...touching(barrels) };
148
+ }
76
149
  return write(edited);
77
150
  }
78
151
 
79
152
  /** Each import after the last catalog import (or at the top), each entry at the object's end. */
80
- function withLocales(source: string, locales: readonly string[]): string | undefined {
153
+ function withLocales(
154
+ source: string,
155
+ locales: readonly string[],
156
+ split: readonly string[],
157
+ ): string | undefined {
81
158
  // Found on the comment-stripped text (same offsets): a `locales: { … }` in a comment above the
82
159
  // call is prose, and it was the one this edited.
83
160
  const object = LOCALES_OBJECT.exec(stripComments(source));
@@ -89,16 +166,16 @@ function withLocales(source: string, locales: readonly string[]): string | undef
89
166
  const body = inner.trim().replace(/,$/, '');
90
167
  const entries = [body, ...locales.map(localeEntry)].filter((part) => part !== '').join(', ');
91
168
  const withEntries = `${source.slice(0, object.index)}${head} ${entries} }${source.slice(object.index + whole.length)}`;
92
- const imports = locales.map(localeImport).join('\n');
169
+ const imports = locales.map((locale) => localeImport(locale, split.includes(locale))).join('\n');
93
170
  const lastImport = [...withEntries.matchAll(CATALOG_IMPORT)].at(-1);
94
171
  if (lastImport === undefined) return `${imports}\n${withEntries}`;
95
172
  const at = lastImport.index + lastImport[0].length;
96
173
  return `${withEntries.slice(0, at)}\n${imports}${withEntries.slice(at)}`;
97
174
  }
98
175
 
99
- const refusal = (locales: readonly string[]): Finding => ({
176
+ const refusal = (locales: readonly string[], split: readonly string[]): Finding => ({
100
177
  code: 'X_CATALOG_UNREGISTERED',
101
178
  cause: `${APP_CATALOGS_PATH} is hand-written in a shape this writer cannot add ${locales.join(', ')} to, so those catalogs are on disk and not selectable`,
102
- fix: `defineCatalogs({ default, locales: { …, ${locales.map(localeEntry).join(', ')} } }) // in ${APP_CATALOGS_PATH}, below ${locales.map(localeImport).join(' ')}`,
179
+ fix: `defineCatalogs({ default, locales: { …, ${locales.map(localeEntry).join(', ')} } }) // in ${APP_CATALOGS_PATH}, below ${locales.map((locale) => localeImport(locale, split.includes(locale))).join(' ')}`,
103
180
  at: APP_CATALOGS_PATH,
104
181
  });
@@ -6,8 +6,9 @@
6
6
  import { DEFAULT_LOCALE, ERROR_DOCS_URL } from '@ultimat3/core';
7
7
  import type { Catalog, Locale } from '@ultimat3/i18n';
8
8
  import { isMiss, placeholdersOf } from '@ultimat3/i18n';
9
+ import type { CatalogLayout } from './catalog-layout';
10
+ import { catalogFileOf } from './catalog-layout';
9
11
  import type { Finding } from './output';
10
- import { catalogPath } from './templates/locales';
11
12
 
12
13
  /**
13
14
  * The length above which two identical values are a copy rather than a name. `Postly`, `Free` and
@@ -41,6 +42,8 @@ const shownValue = (value: string): string =>
41
42
  */
42
43
  export function localeParityFindings(
43
44
  catalogs: Readonly<Record<Locale, Catalog>>,
45
+ /** Each locale's form on disk, so a split locale's finding names the namespace file. */
46
+ layout?: CatalogLayout,
44
47
  ): readonly Finding[] {
45
48
  const reference = catalogs[DEFAULT_LOCALE];
46
49
  if (reference === undefined) return [];
@@ -56,7 +59,11 @@ export function localeParityFindings(
56
59
  // `X_CATALOG_MISSING_KEYS`'s finding. Reporting it here too would be one defect under two
57
60
  // codes, and the second code's repair is not the first one's.
58
61
  if (value === undefined || translated === undefined) continue;
59
- findings.push(...keyFindings(locale, key, value, translated));
62
+ const files = {
63
+ path: catalogFileOf(layout, locale, key),
64
+ reference: catalogFileOf(layout, DEFAULT_LOCALE, key),
65
+ };
66
+ findings.push(...keyFindings(locale, key, value, translated, files));
60
67
  }
61
68
  }
62
69
  return findings;
@@ -76,8 +83,9 @@ function keyFindings(
76
83
  key: string,
77
84
  reference: string,
78
85
  translated: string,
86
+ files: { readonly path: string; readonly reference: string },
79
87
  ): readonly Finding[] {
80
- const path = catalogPath(locale);
88
+ const { path } = files;
81
89
  // A loud miss (`⟦key⟧`) is a placeholder, not a translation, and it carries no slot of its own:
82
90
  // a slot comparison across it blames the marker — `x i18n sync` seeds one into every key
83
91
  // nobody has translated — and prints a fix ("add {name}") that edits the placeholder. The hole
@@ -93,7 +101,7 @@ function keyFindings(
93
101
  if (comparable && extra.length > 0) {
94
102
  findings.push({
95
103
  code: 'X_CATALOG_SLOT_MISMATCH',
96
- cause: `${path} defines "${key}" with ${shownSlots(extra)}, which ${catalogPath(DEFAULT_LOCALE)} does not — interpolate substitutes by name, so ${locale} renders ${shownMisses(extra)}`,
104
+ cause: `${path} defines "${key}" with ${shownSlots(extra)}, which ${files.reference} does not — interpolate substitutes by name, so ${locale} renders ${shownMisses(extra)}`,
97
105
  fix:
98
106
  referenceSlots.length === 0
99
107
  ? `x i18n check --json # remove ${shownSlots(extra)} from "${key}" in ${path}`
@@ -107,7 +115,7 @@ function keyFindings(
107
115
  if (comparable && missing.length > 0) {
108
116
  findings.push({
109
117
  code: 'X_CATALOG_SLOT_MISMATCH',
110
- cause: `${catalogPath(DEFAULT_LOCALE)} defines "${key}" with ${shownSlots(missing)}, which ${path} does not — the value it carries never renders in ${locale}`,
118
+ cause: `${files.reference} defines "${key}" with ${shownSlots(missing)}, which ${path} does not — the value it carries never renders in ${locale}`,
111
119
  fix: `x i18n check --json # add ${shownSlots(missing)} to "${key}" in ${path}`,
112
120
  docs: ERROR_DOCS_URL,
113
121
  at: path,
@@ -122,7 +130,7 @@ function keyFindings(
122
130
  if (translated === reference && reference.length > COPY_LENGTH && !isMiss(reference)) {
123
131
  findings.push({
124
132
  code: 'X_CATALOG_UNTRANSLATED',
125
- cause: `${path} defines "${key}" exactly as ${catalogPath(DEFAULT_LOCALE)} does ("${shownValue(reference)}") — ${reference.length} characters, so ${locale} reads the reference's sentence instead of its own`,
133
+ cause: `${path} defines "${key}" exactly as ${files.reference} does ("${shownValue(reference)}") — ${reference.length} characters, so ${locale} reads the reference's sentence instead of its own`,
126
134
  fix: `x i18n check --json # translate "${key}" in ${path}`,
127
135
  docs: ERROR_DOCS_URL,
128
136
  at: path,
@@ -0,0 +1,75 @@
1
+ // `x i18n add`'s one write: a locale with no catalog yet, created in the form the default locale is
2
+ // in — one flat file, or a directory holding the default's namespace files — and never over a
3
+ // catalog already there, in either form: a flat file beside a directory is `X_CATALOG_LAYOUT_MIXED`.
4
+
5
+ // why: `node:` and not Bun: Bun has no exclusive-create write, and `open(path, 'wx')` / `mkdir`
6
+ // without `recursive` are the only ones there are — `Bun.write` overwrites, so an existence check
7
+ // before it is a race a second `x i18n add` wins. `existsSync` because `Bun.file().exists()`
8
+ // answers false for a directory, and `node:path` because Bun exposes no path API.
9
+ import { existsSync } from 'node:fs';
10
+ import { type FileHandle, mkdir, open } from 'node:fs/promises';
11
+ import { dirname, join } from 'node:path';
12
+ import { stringField } from '@ultimat3/core';
13
+ import type { Catalog } from '@ultimat3/i18n';
14
+ import type { LocaleLayout } from './catalog-layout';
15
+ import { catalogWrites } from './catalog-layout';
16
+ import { CatalogExistsError } from './errors';
17
+ import { catalogDir, catalogPath } from './templates/locales';
18
+
19
+ /**
20
+ * `open`'s and `mkdir`'s failure when the path is already there — the one errno translated here.
21
+ *
22
+ * `stringField`, never `'code' in error && error.code`: `in` narrows for the COMPILER and promises
23
+ * the runtime nothing, so a throwing getter takes the command down one line after the guard.
24
+ */
25
+ const isAlreadyExists = (error: unknown): boolean => stringField(error, 'code') === 'EEXIST';
26
+
27
+ /** Runs the exclusive create, answering `CatalogExistsError` for a path someone got to first. */
28
+ async function exclusive<T>(locale: string, path: string, create: () => Promise<T>): Promise<T> {
29
+ try {
30
+ return await create();
31
+ } catch (error) {
32
+ if (isAlreadyExists(error)) throw new CatalogExistsError({ locale, path });
33
+ throw error;
34
+ }
35
+ }
36
+
37
+ /** The other form already on disk is a catalog too: refused before anything is created. */
38
+ function refuseOtherForm(root: string, locale: string, other: string): void {
39
+ if (existsSync(join(root, other))) throw new CatalogExistsError({ locale, path: other });
40
+ }
41
+
42
+ /**
43
+ * Writes `catalog` as `locale`'s new catalog, shaped like `source` (the default locale's layout),
44
+ * and answers where it landed. The exclusive step is the file itself for a flat locale and the
45
+ * directory for a split one, so two concurrent `x i18n add fr` never both succeed.
46
+ */
47
+ export async function writeNewLocale(
48
+ root: string,
49
+ locale: string,
50
+ catalog: Catalog,
51
+ source: LocaleLayout | undefined,
52
+ ): Promise<string> {
53
+ const split = source?.form === 'split';
54
+ const writes = catalogWrites(locale, catalog, split ? 'split' : 'flat', source?.files);
55
+ if (!split) {
56
+ refuseOtherForm(root, locale, catalogDir(locale));
57
+ const absolute = join(root, catalogPath(locale));
58
+ await mkdir(dirname(absolute), { recursive: true });
59
+ const handle: FileHandle = await exclusive(locale, catalogPath(locale), () =>
60
+ open(absolute, 'wx'),
61
+ );
62
+ try {
63
+ await handle.writeFile(writes[0]?.contents ?? '{}\n');
64
+ } finally {
65
+ await handle.close();
66
+ }
67
+ return catalogPath(locale);
68
+ }
69
+ refuseOtherForm(root, locale, catalogPath(locale));
70
+ const dir = join(root, catalogDir(locale));
71
+ await mkdir(dirname(dir), { recursive: true });
72
+ await exclusive(locale, `${catalogDir(locale)}/`, () => mkdir(dir));
73
+ for (const file of writes) await Bun.write(join(root, file.path), file.contents);
74
+ return `${catalogDir(locale)}/`;
75
+ }