@rivinia/i18n 0.3.3 → 0.5.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.
@@ -0,0 +1,400 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `rivinia-i18n-keys` — generates the typed-key registry for `@rivinia/i18n`
4
+ * and checks key/placeholder parity across dictionaries.
5
+ *
6
+ * npx rivinia-i18n-keys
7
+ * npx rivinia-i18n-keys --source public/i18n/en.json --out src/i18n-keys.d.ts
8
+ * npx rivinia-i18n-keys --check # CI: exit 1 when the file is stale
9
+ * npx rivinia-i18n-keys --parity --dir public/i18n --base en
10
+ *
11
+ * Nested objects flatten to dot paths, literal dotted keys are kept as-is,
12
+ * only string leaves become keys, keys are sorted for stable diffs, and quotes
13
+ * are escaped. No dependencies.
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
16
+ import { dirname, basename, join, relative, resolve } from 'node:path';
17
+
18
+ const DEFAULTS = Object.freeze({
19
+ source: 'public/i18n/en.json',
20
+ out: 'src/i18n-keys.d.ts',
21
+ dir: 'public/i18n',
22
+ base: 'en',
23
+ });
24
+
25
+ const PREFIX = '[rivinia/i18n]';
26
+
27
+ function main(argv) {
28
+ const args = parseArgs(argv);
29
+ if (args.error) {
30
+ console.error(`${PREFIX} ${args.error}`);
31
+ printHelp();
32
+ return 1;
33
+ }
34
+ if (args.help) {
35
+ printHelp();
36
+ return 0;
37
+ }
38
+ return args.parity ? runParity(args) : runGenerate(args);
39
+ }
40
+
41
+ function runGenerate(args) {
42
+ const sourcePath = resolve(args.source ?? DEFAULTS.source);
43
+ const outPath = resolve(args.out ?? DEFAULTS.out);
44
+
45
+ const dictionary = readDictionary(sourcePath);
46
+ if (dictionary === null) return 1;
47
+
48
+ const entries = new Map();
49
+ flatten(dictionary, '', entries);
50
+ const keys = [...entries.keys()].sort();
51
+ const output = render(keys);
52
+
53
+ if (args.check) {
54
+ const current = existsSync(outPath) ? readFileSync(outPath, 'utf8') : null;
55
+ if (current === output) {
56
+ console.log(`${PREFIX} ${outPath} is up to date (${keys.length} keys).`);
57
+ return 0;
58
+ }
59
+ console.error(
60
+ `${PREFIX} ${outPath} is stale. Regenerate it:\n` +
61
+ ` npx rivinia-i18n-keys --source ${relative(process.cwd(), sourcePath)} ` +
62
+ `--out ${relative(process.cwd(), outPath)}`,
63
+ );
64
+ return 1;
65
+ }
66
+
67
+ mkdirSync(dirname(outPath), { recursive: true });
68
+ writeFileSync(outPath, output, 'utf8');
69
+ console.log(`${PREFIX} Wrote ${keys.length} keys to ${outPath}.`);
70
+ return 0;
71
+ }
72
+
73
+ /**
74
+ * `--parity`: every `<lang>.json` in `--dir` must have the same keys as
75
+ * `--base`, and every placeholder used by the base string must appear in the
76
+ * translated string. Sorted output, exit 1 on any mismatch (CI-friendly).
77
+ */
78
+ function runParity(args) {
79
+ const dir = resolve(args.dir ?? DEFAULTS.dir);
80
+ const base = args.base ?? DEFAULTS.base;
81
+
82
+ if (!existsSync(dir)) {
83
+ console.error(`${PREFIX} Dictionary directory not found: ${dir}`);
84
+ return 1;
85
+ }
86
+
87
+ const files = readdirSync(dir)
88
+ .filter((file) => file.endsWith('.json'))
89
+ .sort();
90
+ if (files.length === 0) {
91
+ console.error(`${PREFIX} No JSON dictionaries in ${dir}`);
92
+ return 1;
93
+ }
94
+
95
+ const dictionaries = new Map();
96
+ for (const file of files) {
97
+ const language = basename(file, '.json');
98
+ const path = join(dir, file);
99
+ const dictionary = readDictionary(path);
100
+ if (dictionary === null) return 1;
101
+ const entries = new Map();
102
+ flatten(dictionary, '', entries);
103
+ dictionaries.set(language, entries);
104
+ }
105
+
106
+ const baseEntries = dictionaries.get(base);
107
+ if (baseEntries === undefined) {
108
+ console.error(`${PREFIX} Base dictionary "${base}.json" not found in ${dir}`);
109
+ return 1;
110
+ }
111
+
112
+ const problems = [];
113
+ for (const language of [...dictionaries.keys()].sort()) {
114
+ if (language === base) continue;
115
+ const entries = dictionaries.get(language);
116
+
117
+ for (const key of [...baseEntries.keys()].sort()) {
118
+ if (!entries.has(key)) {
119
+ problems.push(
120
+ `${PREFIX} MISSING ${language} key "${key}" (present in "${base}")`,
121
+ );
122
+ continue;
123
+ }
124
+ const expected = placeholders(baseEntries.get(key).value);
125
+ const actual = placeholders(entries.get(key).value);
126
+ for (const name of [...expected].sort()) {
127
+ if (!actual.has(name)) {
128
+ problems.push(
129
+ `${PREFIX} PLACEHOLDER ${language} key "${key}": ` +
130
+ `{${name}} is used in "${base}" but absent from "${language}"`,
131
+ );
132
+ }
133
+ }
134
+ }
135
+
136
+ for (const key of [...entries.keys()].sort()) {
137
+ if (!baseEntries.has(key)) {
138
+ problems.push(`${PREFIX} EXTRA ${language} key "${key}" (absent in "${base}")`);
139
+ }
140
+ }
141
+ }
142
+
143
+ if (problems.length === 0) {
144
+ console.log(
145
+ `${PREFIX} Parity OK (${dictionaries.size} dictionaries, ` +
146
+ `${baseEntries.size} keys in "${base}").`,
147
+ );
148
+ return 0;
149
+ }
150
+
151
+ for (const line of problems) console.error(line);
152
+ console.error(
153
+ `${PREFIX} ${problems.length} parity problem(s) across ${dictionaries.size} dictionaries.`,
154
+ );
155
+ return 1;
156
+ }
157
+
158
+ function readDictionary(path) {
159
+ if (!existsSync(path)) {
160
+ console.error(`${PREFIX} Source dictionary not found: ${path}`);
161
+ return null;
162
+ }
163
+ try {
164
+ return JSON.parse(readFileSync(path, 'utf8'));
165
+ } catch (error) {
166
+ console.error(`${PREFIX} Could not parse ${path}: ${error.message}`);
167
+ return null;
168
+ }
169
+ }
170
+
171
+ function parseArgs(argv) {
172
+ const args = {};
173
+ for (let i = 0; i < argv.length; i++) {
174
+ const arg = argv[i];
175
+ if (arg === '--check') {
176
+ args.check = true;
177
+ } else if (arg === '--parity') {
178
+ args.parity = true;
179
+ } else if (arg === '--help' || arg === '-h') {
180
+ args.help = true;
181
+ } else if (arg === '--source' || arg === '--out' || arg === '--dir' || arg === '--base') {
182
+ const value = argv[i + 1];
183
+ if (value === undefined || value.startsWith('--')) {
184
+ return { error: `${arg} needs a ${arg === '--base' ? 'language' : 'path'}.` };
185
+ }
186
+ args[arg.slice(2)] = value;
187
+ i++;
188
+ } else if (
189
+ arg.startsWith('--source=') ||
190
+ arg.startsWith('--out=') ||
191
+ arg.startsWith('--dir=') ||
192
+ arg.startsWith('--base=')
193
+ ) {
194
+ const eq = arg.indexOf('=');
195
+ args[arg.slice(2, eq)] = arg.slice(eq + 1);
196
+ } else {
197
+ return { error: `Unknown option: ${arg}` };
198
+ }
199
+ }
200
+ return args;
201
+ }
202
+
203
+ /**
204
+ * Collects string leaves in `entries` (key → { value, flat, sourcePath }).
205
+ * A JSON key that itself contains dots (an export from many tools) is already
206
+ * a full key; when it collides with a nested path the literal key wins and a
207
+ * warning is printed.
208
+ */
209
+ function flatten(value, prefix, entries) {
210
+ if (Array.isArray(value)) {
211
+ warn(`Skipping array at "${prefix || '(root)'}" — arrays are not keys.`);
212
+ return;
213
+ }
214
+ if (value !== null && typeof value === 'object') {
215
+ for (const [key, child] of Object.entries(value)) {
216
+ const path = prefix ? `${prefix}.${key}` : key;
217
+ if (child !== null && typeof child === 'object' && !Array.isArray(child)) {
218
+ flatten(child, path, entries);
219
+ continue;
220
+ }
221
+ if (typeof child === 'string') {
222
+ addEntry(entries, path, child, key.includes('.'), path);
223
+ continue;
224
+ }
225
+ if (Array.isArray(child)) {
226
+ warn(`Skipping array at "${path}" — arrays are not keys.`);
227
+ continue;
228
+ }
229
+ warn(`Skipping non-string value at "${path}" (${typeOf(child)}).`);
230
+ }
231
+ return;
232
+ }
233
+ warn(`Skipping non-string value at "${prefix || '(root)'}" (${typeOf(value)}).`);
234
+ }
235
+
236
+ function addEntry(entries, key, value, flat, sourcePath) {
237
+ const existing = entries.get(key);
238
+ if (existing === undefined) {
239
+ entries.set(key, { value, flat, sourcePath });
240
+ return;
241
+ }
242
+ if (existing.flat && !flat) {
243
+ warn(`Key collision at "${key}": keeping the flat key over "${sourcePath}".`);
244
+ return;
245
+ }
246
+ if (!existing.flat && flat) {
247
+ warn(`Key collision at "${key}": the flat key wins over "${existing.sourcePath}".`);
248
+ entries.set(key, { value, flat, sourcePath });
249
+ return;
250
+ }
251
+ warn(
252
+ `Key collision at "${key}" between "${existing.sourcePath}" and "${sourcePath}"; ` +
253
+ 'keeping the first value.',
254
+ );
255
+ }
256
+
257
+ const NAME = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
258
+ const BRANCH_TYPES = new Set(['plural', 'selectordinal', 'select']);
259
+
260
+ /**
261
+ * Named arguments of an ICU message: every `{name …}` argument at any nesting
262
+ * depth. Branch bodies are message text, not arguments, so their words are
263
+ * never reported — `=0 {No items}` must not yield a `{No}` parameter.
264
+ */
265
+ function placeholders(message) {
266
+ const names = new Set();
267
+ if (typeof message !== 'string') return names;
268
+ collectPlaceholders(message, 0, message.length, names);
269
+ return names;
270
+ }
271
+
272
+ function collectPlaceholders(text, start, end, names) {
273
+ let i = start;
274
+ while (i < end) {
275
+ const char = text[i];
276
+ if (char === "'") {
277
+ i = skipQuote(text, i, end);
278
+ } else if (char === '{') {
279
+ i = readArgument(text, i, end, names);
280
+ } else {
281
+ i++;
282
+ }
283
+ }
284
+ }
285
+
286
+ /** ICU: `''` is one apostrophe; `'` before `{`, `}` or `#` quotes until `'`. */
287
+ function skipQuote(text, i, end) {
288
+ if (text[i + 1] === "'") return i + 2;
289
+ const next = text[i + 1];
290
+ if (next === '{' || next === '}' || next === '#') {
291
+ const close = text.indexOf("'", i + 2);
292
+ return close === -1 || close >= end ? end : close + 1;
293
+ }
294
+ return i + 1;
295
+ }
296
+
297
+ /** Index of the `}` closing the `{` at `open`; `end` when malformed. */
298
+ function matchBrace(text, open, end) {
299
+ let depth = 0;
300
+ for (let i = open; i < end; i++) {
301
+ const char = text[i];
302
+ if (char === "'") {
303
+ i = skipQuote(text, i, end) - 1;
304
+ } else if (char === '{') {
305
+ depth++;
306
+ } else if (char === '}' && --depth === 0) {
307
+ return i;
308
+ }
309
+ }
310
+ return end;
311
+ }
312
+
313
+ function readArgument(text, open, end, names) {
314
+ const close = matchBrace(text, open, end);
315
+ let i = open + 1;
316
+ while (i < close && /\s/.test(text[i])) i++;
317
+ const nameStart = i;
318
+ while (i < close && text[i] !== ',' && text[i] !== '}') i++;
319
+ const name = text.slice(nameStart, i).trim();
320
+ if (NAME.test(name)) names.add(name);
321
+ if (i >= close || text[i] === '}') return close + 1;
322
+
323
+ i++; // past the comma
324
+ while (i < close && /\s/.test(text[i])) i++;
325
+ const typeStart = i;
326
+ while (i < close && text[i] !== ',' && text[i] !== '}') i++;
327
+ if (BRANCH_TYPES.has(text.slice(typeStart, i).trim())) {
328
+ collectBranches(text, i, close, names);
329
+ }
330
+ return close + 1;
331
+ }
332
+
333
+ /** Selector words are ignored; each `{…}` branch body is a nested message. */
334
+ function collectBranches(text, start, end, names) {
335
+ let i = start;
336
+ while (i < end) {
337
+ const char = text[i];
338
+ if (char === "'") {
339
+ i = skipQuote(text, i, end);
340
+ } else if (char === '{') {
341
+ const close = matchBrace(text, i, end);
342
+ collectPlaceholders(text, i + 1, close, names);
343
+ i = close + 1;
344
+ } else {
345
+ i++;
346
+ }
347
+ }
348
+ }
349
+
350
+ function typeOf(value) {
351
+ if (value === null) return 'null';
352
+ return typeof value;
353
+ }
354
+
355
+ function warn(message) {
356
+ console.warn(`${PREFIX} ${message}`);
357
+ }
358
+
359
+ function render(keys) {
360
+ const union = keys.length === 0 ? 'never' : keys.map((key) => `'${escapeKey(key)}'`).join(' | ');
361
+ return [
362
+ '// Generated by @rivinia/i18n. Do not edit.',
363
+ "import '@rivinia/i18n';",
364
+ '',
365
+ "declare module '@rivinia/i18n' {",
366
+ ' interface RiviniaI18nKeyRegistry {',
367
+ ` readonly keys: ${union};`,
368
+ ' }',
369
+ '}',
370
+ '',
371
+ ].join('\n');
372
+ }
373
+
374
+ function escapeKey(key) {
375
+ return key.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
376
+ }
377
+
378
+ function printHelp() {
379
+ console.log(
380
+ [
381
+ 'rivinia-i18n-keys — generate typed translation keys for @rivinia/i18n',
382
+ '',
383
+ 'Usage:',
384
+ ' rivinia-i18n-keys [--source <json>] [--out <d.ts>]',
385
+ ' rivinia-i18n-keys --check',
386
+ ' rivinia-i18n-keys --parity [--dir <folder>] [--base <language>]',
387
+ '',
388
+ 'Options:',
389
+ ` --source Dictionary to read (default: ${DEFAULTS.source})`,
390
+ ` --out Declaration file to write (default: ${DEFAULTS.out})`,
391
+ ' --check Exit 1 when --out is missing or stale (for CI)',
392
+ ` --parity Compare every dictionary against the base`,
393
+ ` --dir Dictionary folder (default: ${DEFAULTS.dir})`,
394
+ ` --base Reference language (default: ${DEFAULTS.base})`,
395
+ ' --help Show this help',
396
+ ].join('\n'),
397
+ );
398
+ }
399
+
400
+ process.exitCode = main(process.argv.slice(2));
@@ -0,0 +1,20 @@
1
+ var HttpLoader = class {
2
+ _options;
3
+ _resolveUrl;
4
+ _createError;
5
+ constructor(_options, _resolveUrl, _createError) {
6
+ this._options = _options;
7
+ this._resolveUrl = _resolveUrl;
8
+ this._createError = _createError;
9
+ }
10
+ async load(language, context) {
11
+ const built = this._options.buildUrl?.(language) ?? `${this._options.endpoint}/${language}`;
12
+ const url = this._resolveUrl(built, context);
13
+ const response = await fetch(url, { method: this._options.method ?? "GET" });
14
+ if (!response.ok) throw this._createError(url, response.status, language);
15
+ return response.json();
16
+ }
17
+ };
18
+ export { HttpLoader };
19
+
20
+ //# sourceMappingURL=rivinia-i18n-http-loader.impl-sLjTazQZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rivinia-i18n-http-loader.impl-sLjTazQZ.mjs","names":[],"sources":["../../../projects/i18n/src/lib/services/http-loader.impl.ts"],"sourcesContent":["import type { HttpLoaderOptions, LoaderContext, TranslationLoader } from '../models/loaders';\n\ntype ResolveUrl = (url: string, context?: LoaderContext) => string;\ntype CreateError = (url: string, status: number, language: string) => Error;\n\nexport class HttpLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(\n private readonly _options: HttpLoaderOptions,\n private readonly _resolveUrl: ResolveUrl,\n private readonly _createError: CreateError,\n ) {}\n\n async load(language: L, context?: LoaderContext): Promise<Record<string, unknown>> {\n const built = this._options.buildUrl?.(language) ?? `${this._options.endpoint}/${language}`;\n const url = this._resolveUrl(built, context);\n const response = await fetch(url, { method: this._options.method ?? 'GET' });\n if (!response.ok) {\n throw this._createError(url, response.status, language);\n }\n return response.json();\n }\n}\n"],"mappings":"AAKA,IAAa,aAAb,MAAuB;CAEF;CACA;CACA;CAHnB,YACmB,UACA,aACA,cAAyB;EAFzB,KAAA,WAAA;EACA,KAAA,cAAA;EACA,KAAA,eAAA;CAChB;CAEH,MAAM,KAAK,UAAa,SAAuB;EAC7C,MAAM,QAAQ,KAAK,SAAS,WAAW,QAAQ,KAAK,GAAG,KAAK,SAAS,SAAQ,GAAI;EACjF,MAAM,MAAM,KAAK,YAAY,OAAO,OAAO;EAC3C,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,UAAU,MAAK,CAAE;EAC3E,IAAI,CAAC,SAAS,IACZ,MAAM,KAAK,aAAa,KAAK,SAAS,QAAQ,QAAQ;EAExD,OAAO,SAAS,KAAI;CACtB;AACD"}
@@ -0,0 +1,19 @@
1
+ var RemoteLoader = class {
2
+ _options;
3
+ _resolveUrl;
4
+ _createError;
5
+ constructor(_options, _resolveUrl, _createError) {
6
+ this._options = _options;
7
+ this._resolveUrl = _resolveUrl;
8
+ this._createError = _createError;
9
+ }
10
+ async load(language, context) {
11
+ const url = this._resolveUrl(this._options.url(language), context);
12
+ const response = await fetch(url, { headers: this._options.headers });
13
+ if (!response.ok) throw this._createError(url, response.status, language);
14
+ return response.json();
15
+ }
16
+ };
17
+ export { RemoteLoader };
18
+
19
+ //# sourceMappingURL=rivinia-i18n-remote-loader.impl-DE90KQn_.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rivinia-i18n-remote-loader.impl-DE90KQn_.mjs","names":[],"sources":["../../../projects/i18n/src/lib/services/remote-loader.impl.ts"],"sourcesContent":["import type { LoaderContext, RemoteLoaderOptions, TranslationLoader } from '../models/loaders';\n\ntype ResolveUrl = (url: string, context?: LoaderContext) => string;\ntype CreateError = (url: string, status: number, language: string) => Error;\n\nexport class RemoteLoader<L extends string = string> implements TranslationLoader<L> {\n constructor(\n private readonly _options: RemoteLoaderOptions,\n private readonly _resolveUrl: ResolveUrl,\n private readonly _createError: CreateError,\n ) {}\n\n async load(language: L, context?: LoaderContext): Promise<Record<string, unknown>> {\n const url = this._resolveUrl(this._options.url(language), context);\n const response = await fetch(url, { headers: this._options.headers });\n if (!response.ok) {\n throw this._createError(url, response.status, language);\n }\n return response.json();\n }\n}\n"],"mappings":"AAKA,IAAa,eAAb,MAAyB;CAEJ;CACA;CACA;CAHnB,YACmB,UACA,aACA,cAAyB;EAFzB,KAAA,WAAA;EACA,KAAA,cAAA;EACA,KAAA,eAAA;CAChB;CAEH,MAAM,KAAK,UAAa,SAAuB;EAC7C,MAAM,MAAM,KAAK,YAAY,KAAK,SAAS,IAAI,QAAQ,GAAG,OAAO;EACjE,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,SAAS,KAAK,SAAS,QAAO,CAAE;EACpE,IAAI,CAAC,SAAS,IACZ,MAAM,KAAK,aAAa,KAAK,SAAS,QAAQ,QAAQ;EAExD,OAAO,SAAS,KAAI;CACtB;AACD"}