@hakistack/i18n 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/cli/bin.cjs +940 -0
- package/fesm2022/hakistack-i18n-engine.mjs +339 -0
- package/fesm2022/hakistack-i18n-engine.mjs.map +1 -0
- package/fesm2022/hakistack-i18n.mjs +475 -0
- package/fesm2022/hakistack-i18n.mjs.map +1 -0
- package/package.json +61 -4
- package/schematics/collection.json +15 -0
- package/schematics/ng-add/index.cjs +301 -0
- package/schematics/ng-add/index.cjs.map +1 -0
- package/schematics/ng-add/schema.js +3 -0
- package/schematics/ng-add/schema.js.map +1 -0
- package/schematics/ng-add/schema.json +37 -0
- package/types/hakistack-i18n-engine.d.ts +260 -0
- package/types/hakistack-i18n.d.ts +334 -0
package/cli/bin.cjs
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
+
mod
|
|
24
|
+
));
|
|
25
|
+
|
|
26
|
+
// projects/hakistack/i18n/cli/bin.ts
|
|
27
|
+
var path7 = __toESM(require("path"));
|
|
28
|
+
|
|
29
|
+
// projects/hakistack/i18n/cli/config.ts
|
|
30
|
+
var fs = __toESM(require("fs"));
|
|
31
|
+
var path = __toESM(require("path"));
|
|
32
|
+
var import_jiti = require("jiti");
|
|
33
|
+
|
|
34
|
+
// projects/hakistack/i18n/engine/define-translations.ts
|
|
35
|
+
var SOURCE_LANG = "en";
|
|
36
|
+
var TRANSLATION_BRAND = /* @__PURE__ */ Symbol.for("@hakistack/i18n:translation-value");
|
|
37
|
+
function isTranslationValue(value) {
|
|
38
|
+
return value !== null && typeof value === "object" && value[TRANSLATION_BRAND] === true;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// projects/hakistack/i18n/cli/config.ts
|
|
42
|
+
var CONFIG_BASENAMES = [
|
|
43
|
+
"i18n.config.ts",
|
|
44
|
+
"i18n.config.mts",
|
|
45
|
+
"i18n.config.cts",
|
|
46
|
+
"i18n.config.js",
|
|
47
|
+
"i18n.config.mjs",
|
|
48
|
+
"i18n.config.cjs",
|
|
49
|
+
"i18n.config.json"
|
|
50
|
+
];
|
|
51
|
+
var DEFAULTS = {
|
|
52
|
+
srcRoot: "src",
|
|
53
|
+
definitionsDir: "src/i18n/definitions",
|
|
54
|
+
outputDir: "src/assets/i18n",
|
|
55
|
+
locales: ["en"],
|
|
56
|
+
packageName: "@hakistack/i18n",
|
|
57
|
+
directiveSelector: "appTranslate",
|
|
58
|
+
directiveClassName: "AppTranslateDirective"
|
|
59
|
+
};
|
|
60
|
+
function findConfigFile(cwd) {
|
|
61
|
+
for (const basename2 of CONFIG_BASENAMES) {
|
|
62
|
+
const candidate = path.join(cwd, basename2);
|
|
63
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
async function loadConfig(cwd, overrides = {}) {
|
|
68
|
+
let fileConfig = {};
|
|
69
|
+
const configPath = findConfigFile(cwd);
|
|
70
|
+
if (configPath) {
|
|
71
|
+
if (configPath.endsWith(".json")) {
|
|
72
|
+
fileConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
|
|
73
|
+
} else {
|
|
74
|
+
const jiti = (0, import_jiti.createJiti)(__filename);
|
|
75
|
+
const mod = await jiti.import(configPath);
|
|
76
|
+
fileConfig = mod.default ?? mod;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const legacySourceLang = fileConfig.sourceLang;
|
|
80
|
+
if (legacySourceLang !== void 0 && legacySourceLang !== SOURCE_LANG) {
|
|
81
|
+
throw new Error(
|
|
82
|
+
`i18n: 'sourceLang' is not configurable \u2014 the source locale is always '${SOURCE_LANG}' (t()'s first argument). Remove 'sourceLang' from ${configPath ?? "the config"}.`
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
const merged = { ...DEFAULTS, ...stripUndefined(fileConfig), ...stripUndefined(overrides) };
|
|
86
|
+
const requested = merged.locales && merged.locales.length > 0 ? merged.locales : DEFAULTS.locales;
|
|
87
|
+
const locales = requested.includes(SOURCE_LANG) ? requested : [SOURCE_LANG, ...requested];
|
|
88
|
+
return {
|
|
89
|
+
cwd,
|
|
90
|
+
srcRoot: path.resolve(cwd, merged.srcRoot),
|
|
91
|
+
definitionsDir: path.resolve(cwd, merged.definitionsDir),
|
|
92
|
+
outputDir: path.resolve(cwd, merged.outputDir),
|
|
93
|
+
locales,
|
|
94
|
+
sourceLang: SOURCE_LANG,
|
|
95
|
+
packageName: merged.packageName,
|
|
96
|
+
directiveSelector: merged.directiveSelector,
|
|
97
|
+
directiveClassName: merged.directiveClassName
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function stripUndefined(obj) {
|
|
101
|
+
const out = {};
|
|
102
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
103
|
+
if (v !== void 0) out[k] = v;
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// projects/hakistack/i18n/cli/find-unused.ts
|
|
109
|
+
var fs3 = __toESM(require("fs"));
|
|
110
|
+
var path3 = __toESM(require("path"));
|
|
111
|
+
|
|
112
|
+
// projects/hakistack/i18n/cli/load-registry.ts
|
|
113
|
+
var fs2 = __toESM(require("fs"));
|
|
114
|
+
var path2 = __toESM(require("path"));
|
|
115
|
+
var import_jiti2 = require("jiti");
|
|
116
|
+
function barrelPath(config) {
|
|
117
|
+
return path2.join(config.definitionsDir, "index.generated.ts");
|
|
118
|
+
}
|
|
119
|
+
function keysPath(config) {
|
|
120
|
+
return path2.join(config.definitionsDir, "keys.generated.ts");
|
|
121
|
+
}
|
|
122
|
+
function ensureExists(file, hint) {
|
|
123
|
+
if (!fs2.existsSync(file)) {
|
|
124
|
+
throw new Error(`i18n: expected generated file not found:
|
|
125
|
+
${file}
|
|
126
|
+
${hint}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async function loadRegistry(config) {
|
|
130
|
+
const file = barrelPath(config);
|
|
131
|
+
ensureExists(file, "Run the `scan` command first (`hakistack-i18n scan`).");
|
|
132
|
+
const jiti = (0, import_jiti2.createJiti)(__filename);
|
|
133
|
+
const mod = await jiti.import(file);
|
|
134
|
+
if (!mod.ALL_TRANSLATIONS) {
|
|
135
|
+
throw new Error(`i18n: '${file}' does not export ALL_TRANSLATIONS. Re-run the scan.`);
|
|
136
|
+
}
|
|
137
|
+
return mod.ALL_TRANSLATIONS;
|
|
138
|
+
}
|
|
139
|
+
async function loadKeys(config) {
|
|
140
|
+
const file = keysPath(config);
|
|
141
|
+
ensureExists(file, "Run the `scan` command first (`hakistack-i18n scan`).");
|
|
142
|
+
const jiti = (0, import_jiti2.createJiti)(__filename);
|
|
143
|
+
const mod = await jiti.import(file);
|
|
144
|
+
if (!mod.TK) {
|
|
145
|
+
throw new Error(`i18n: '${file}' does not export TK. Re-run the scan.`);
|
|
146
|
+
}
|
|
147
|
+
return mod.TK;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// projects/hakistack/i18n/cli/find-unused.ts
|
|
151
|
+
var EXCLUDED_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "out-tsc", ".angular", ".cache"]);
|
|
152
|
+
var TEST_FILE_RE = /\.spec\.ts$/;
|
|
153
|
+
var I18N_FILE_RE = /\.i18n\.ts$/;
|
|
154
|
+
var GENERATED_RE = /\.generated\.ts$/;
|
|
155
|
+
var SCANNABLE_RE = /\.(ts|html)$/;
|
|
156
|
+
var LITERAL_RE = /['"`]([a-z][a-zA-Z0-9_.]*?)['"`]/g;
|
|
157
|
+
var ACCESSOR_RE = /\bTK(?:\.[a-zA-Z][a-zA-Z0-9_]*)+\b/g;
|
|
158
|
+
var MARKER_RE = /\/\*\s*i18n-used:\s*([^*]+?)\s*\*\//g;
|
|
159
|
+
function escapeRegex(s) {
|
|
160
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
161
|
+
}
|
|
162
|
+
function contextVarRegex(directiveSelector) {
|
|
163
|
+
return new RegExp(`\\*?${escapeRegex(directiveSelector)}\\s*=\\s*["'][^"']*?let\\s+([a-zA-Z_$][\\w$]*)`, "g");
|
|
164
|
+
}
|
|
165
|
+
function contextVars(content, re) {
|
|
166
|
+
const vars = /* @__PURE__ */ new Set();
|
|
167
|
+
for (const m of content.matchAll(re)) vars.add(m[1]);
|
|
168
|
+
return [...vars];
|
|
169
|
+
}
|
|
170
|
+
function walkLeafStrings(node, out) {
|
|
171
|
+
if (typeof node === "string") {
|
|
172
|
+
out.add(node);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (node && typeof node === "object") for (const v of Object.values(node)) walkLeafStrings(v, out);
|
|
176
|
+
}
|
|
177
|
+
function walkTKAccessors(node, accessor, out) {
|
|
178
|
+
if (typeof node === "string") {
|
|
179
|
+
out.set(accessor.join("."), node);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
if (node && typeof node === "object") for (const [k, v] of Object.entries(node)) walkTKAccessors(v, [...accessor, k], out);
|
|
183
|
+
}
|
|
184
|
+
function* walkSourceFiles(dir) {
|
|
185
|
+
if (!fs3.existsSync(dir)) return;
|
|
186
|
+
for (const entry of fs3.readdirSync(dir, { withFileTypes: true })) {
|
|
187
|
+
if (entry.name.startsWith(".") || EXCLUDED_DIRS.has(entry.name)) continue;
|
|
188
|
+
const full = path3.join(dir, entry.name);
|
|
189
|
+
if (entry.isDirectory()) yield* walkSourceFiles(full);
|
|
190
|
+
else if (entry.isFile() && SCANNABLE_RE.test(entry.name)) yield full;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function lineOf(content, charIndex) {
|
|
194
|
+
let line = 1;
|
|
195
|
+
for (let i = 0; i < charIndex; i++) if (content.charCodeAt(i) === 10) line++;
|
|
196
|
+
return line;
|
|
197
|
+
}
|
|
198
|
+
function patternToRegex(claimed) {
|
|
199
|
+
const escaped = claimed.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
200
|
+
return new RegExp("^" + escaped + "$");
|
|
201
|
+
}
|
|
202
|
+
async function runFindUnused(config, opts = {}) {
|
|
203
|
+
const registry = await loadRegistry(config);
|
|
204
|
+
const tk = await loadKeys(config);
|
|
205
|
+
const allKeys = /* @__PURE__ */ new Set();
|
|
206
|
+
for (const mod of registry) walkLeafStrings(mod.keys, allKeys);
|
|
207
|
+
const accessorMap = /* @__PURE__ */ new Map();
|
|
208
|
+
walkTKAccessors(tk, ["TK"], accessorMap);
|
|
209
|
+
const keyToAccessors = /* @__PURE__ */ new Map();
|
|
210
|
+
for (const [acc, key] of accessorMap) {
|
|
211
|
+
const list = keyToAccessors.get(key) ?? [];
|
|
212
|
+
list.push(acc);
|
|
213
|
+
keyToAccessors.set(key, list);
|
|
214
|
+
}
|
|
215
|
+
const status = /* @__PURE__ */ new Map();
|
|
216
|
+
for (const key of allKeys) {
|
|
217
|
+
status.set(key, { key, accessors: keyToAccessors.get(key) ?? [], prodRefs: [], testRefs: [], claimedByMarker: false });
|
|
218
|
+
}
|
|
219
|
+
const contextVarRe = contextVarRegex(config.directiveSelector);
|
|
220
|
+
for (const file of walkSourceFiles(config.srcRoot)) {
|
|
221
|
+
if (I18N_FILE_RE.test(file) || GENERATED_RE.test(file)) continue;
|
|
222
|
+
const isTest = TEST_FILE_RE.test(file);
|
|
223
|
+
const relFile = path3.relative(config.cwd, file);
|
|
224
|
+
const content = fs3.readFileSync(file, "utf-8");
|
|
225
|
+
for (const m of content.matchAll(MARKER_RE)) {
|
|
226
|
+
const pattern = patternToRegex(m[1].trim());
|
|
227
|
+
for (const [key, st] of status) if (pattern.test(key)) st.claimedByMarker = true;
|
|
228
|
+
}
|
|
229
|
+
for (const m of content.matchAll(LITERAL_RE)) {
|
|
230
|
+
const st = status.get(m[1]);
|
|
231
|
+
if (!st) continue;
|
|
232
|
+
(isTest ? st.testRefs : st.prodRefs).push({ file: relFile, line: lineOf(content, m.index ?? 0) });
|
|
233
|
+
}
|
|
234
|
+
for (const m of content.matchAll(ACCESSOR_RE)) {
|
|
235
|
+
const key = accessorMap.get(m[0]);
|
|
236
|
+
if (!key) continue;
|
|
237
|
+
const st = status.get(key);
|
|
238
|
+
if (!st) continue;
|
|
239
|
+
(isTest ? st.testRefs : st.prodRefs).push({ file: relFile, line: lineOf(content, m.index ?? 0) });
|
|
240
|
+
}
|
|
241
|
+
for (const varName of contextVars(content, contextVarRe)) {
|
|
242
|
+
const re = new RegExp(`\\b${escapeRegex(varName)}((?:\\.[a-zA-Z_$][\\w$]*)+)`, "g");
|
|
243
|
+
for (const m of content.matchAll(re)) {
|
|
244
|
+
const st = status.get(m[1].slice(1));
|
|
245
|
+
if (!st) continue;
|
|
246
|
+
(isTest ? st.testRefs : st.prodRefs).push({ file: relFile, line: lineOf(content, m.index ?? 0) });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const unused = [];
|
|
251
|
+
const testOnly = [];
|
|
252
|
+
const claimed = [];
|
|
253
|
+
const used = [];
|
|
254
|
+
for (const st of status.values()) {
|
|
255
|
+
if (st.claimedByMarker) claimed.push(st);
|
|
256
|
+
else if (st.prodRefs.length) used.push(st);
|
|
257
|
+
else if (st.testRefs.length) testOnly.push(st);
|
|
258
|
+
else unused.push(st);
|
|
259
|
+
}
|
|
260
|
+
for (const bucket of [unused, testOnly]) bucket.sort((a, b) => a.key.localeCompare(b.key));
|
|
261
|
+
console.log("\n\u{1F50D} i18n unused-key detector\n" + "=".repeat(50));
|
|
262
|
+
if (!unused.length && !testOnly.length) {
|
|
263
|
+
console.log(`
|
|
264
|
+
\u2713 All ${allKeys.size} keys are referenced.`);
|
|
265
|
+
if (claimed.length) console.log(` (${claimed.length} claimed via /* i18n-used */ markers)`);
|
|
266
|
+
console.log("");
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (unused.length) {
|
|
270
|
+
console.log(`
|
|
271
|
+
\u274C Unused (${unused.length}):
|
|
272
|
+
`);
|
|
273
|
+
for (const st of unused) console.log(` ${st.key}`);
|
|
274
|
+
}
|
|
275
|
+
if (testOnly.length) {
|
|
276
|
+
console.log(`
|
|
277
|
+
\u26A0\uFE0F Test-only (${testOnly.length}) \u2014 referenced ONLY in *.spec.ts:
|
|
278
|
+
`);
|
|
279
|
+
for (const st of testOnly) {
|
|
280
|
+
console.log(` ${st.key}`);
|
|
281
|
+
if (opts.verbose) for (const ref of st.testRefs.slice(0, 3)) console.log(` ${ref.file}:${ref.line}`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
console.log(
|
|
285
|
+
`
|
|
286
|
+
\u{1F4CA} Summary
|
|
287
|
+
Total: ${allKeys.size} Used: ${used.length} Test-only: ${testOnly.length} Claimed: ${claimed.length} Unused: ${unused.length}
|
|
288
|
+
`
|
|
289
|
+
);
|
|
290
|
+
if (opts.strict && unused.length) {
|
|
291
|
+
console.log("\u274C --strict: failing because unused keys were found.\n");
|
|
292
|
+
process.exitCode = 1;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// projects/hakistack/i18n/cli/generate.ts
|
|
297
|
+
var fs4 = __toESM(require("fs"));
|
|
298
|
+
var path4 = __toESM(require("path"));
|
|
299
|
+
|
|
300
|
+
// projects/hakistack/i18n/engine/build-tree.ts
|
|
301
|
+
function getTranslation(value, lang, defaultLang) {
|
|
302
|
+
const byLang = value;
|
|
303
|
+
if (lang === defaultLang) {
|
|
304
|
+
return byLang[defaultLang] ?? value.en;
|
|
305
|
+
}
|
|
306
|
+
return byLang[lang] ?? byLang[defaultLang] ?? value.en;
|
|
307
|
+
}
|
|
308
|
+
function extractLanguage(translations, lang, defaultLang) {
|
|
309
|
+
const result = {};
|
|
310
|
+
for (const [key, value] of Object.entries(translations)) {
|
|
311
|
+
if (isTranslationValue(value)) {
|
|
312
|
+
result[key] = getTranslation(value, lang, defaultLang);
|
|
313
|
+
if (value.__comment) {
|
|
314
|
+
result[`${key}.comment`] = value.__comment;
|
|
315
|
+
}
|
|
316
|
+
} else if (typeof value === "object" && value !== null) {
|
|
317
|
+
result[key] = extractLanguage(value, lang, defaultLang);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return result;
|
|
321
|
+
}
|
|
322
|
+
function setAtScope(target, scope, subtree) {
|
|
323
|
+
const parts = scope.split(".");
|
|
324
|
+
let current = target;
|
|
325
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
326
|
+
const part = parts[i];
|
|
327
|
+
const slot = current[part];
|
|
328
|
+
if (slot === void 0 || typeof slot === "string") {
|
|
329
|
+
current[part] = {};
|
|
330
|
+
}
|
|
331
|
+
current = current[part];
|
|
332
|
+
}
|
|
333
|
+
const leaf = parts[parts.length - 1];
|
|
334
|
+
const existing = current[leaf];
|
|
335
|
+
if (existing && typeof existing === "object") {
|
|
336
|
+
Object.assign(existing, subtree);
|
|
337
|
+
} else {
|
|
338
|
+
current[leaf] = subtree;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
function buildLanguageTree(registry, lang, defaultLang) {
|
|
342
|
+
const tree = {};
|
|
343
|
+
for (const mod of registry) {
|
|
344
|
+
const subtree = extractLanguage(mod.translations, lang, defaultLang);
|
|
345
|
+
setAtScope(tree, mod.scope, subtree);
|
|
346
|
+
}
|
|
347
|
+
return tree;
|
|
348
|
+
}
|
|
349
|
+
function buildScopedTree(registry, lang, defaultLang, scope) {
|
|
350
|
+
const wanted = normalizeScope(scope);
|
|
351
|
+
for (const mod of registry) {
|
|
352
|
+
if (mod.scoped && normalizeScope(mod.scope) === wanted) {
|
|
353
|
+
return extractLanguage(mod.translations, lang, defaultLang);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
function scopeToFilesystemPath(scope) {
|
|
359
|
+
return scope.replace(/\./g, "/");
|
|
360
|
+
}
|
|
361
|
+
function normalizeScope(scope) {
|
|
362
|
+
return scope.replace(/\//g, ".");
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// projects/hakistack/i18n/cli/generate.ts
|
|
366
|
+
function analyze(translations, lang, defaultLang, prefix = "") {
|
|
367
|
+
let total = 0;
|
|
368
|
+
let translated = 0;
|
|
369
|
+
const missing = [];
|
|
370
|
+
for (const [key, value] of Object.entries(translations)) {
|
|
371
|
+
const currentPath = prefix ? `${prefix}.${key}` : key;
|
|
372
|
+
if (isTranslationValue(value)) {
|
|
373
|
+
total++;
|
|
374
|
+
if (value[lang]) {
|
|
375
|
+
translated++;
|
|
376
|
+
} else if (lang !== defaultLang) {
|
|
377
|
+
missing.push(currentPath);
|
|
378
|
+
}
|
|
379
|
+
} else if (typeof value === "object" && value !== null) {
|
|
380
|
+
const nested = analyze(value, lang, defaultLang, currentPath);
|
|
381
|
+
total += nested.total;
|
|
382
|
+
translated += nested.translated;
|
|
383
|
+
missing.push(...nested.missing);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return { total, translated, missing };
|
|
387
|
+
}
|
|
388
|
+
async function runGenerate(config) {
|
|
389
|
+
console.log("\n\u{1F310} i18n JSON generation\n" + "=".repeat(50));
|
|
390
|
+
const registry = await loadRegistry(config);
|
|
391
|
+
fs4.mkdirSync(config.outputDir, { recursive: true });
|
|
392
|
+
let totalKeys = 0;
|
|
393
|
+
const translatedByLang = {};
|
|
394
|
+
const missingByLang = {};
|
|
395
|
+
for (const lang of config.locales) {
|
|
396
|
+
translatedByLang[lang] = 0;
|
|
397
|
+
missingByLang[lang] = [];
|
|
398
|
+
for (const mod of registry) {
|
|
399
|
+
const a = analyze(mod.translations, lang, SOURCE_LANG, mod.scope);
|
|
400
|
+
if (lang === SOURCE_LANG) totalKeys += a.total;
|
|
401
|
+
translatedByLang[lang] += a.translated;
|
|
402
|
+
missingByLang[lang].push(...a.missing);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
const scopedModules = registry.filter((m) => m.scoped);
|
|
406
|
+
for (const lang of config.locales) {
|
|
407
|
+
const rootTree = buildLanguageTree(registry, lang, SOURCE_LANG);
|
|
408
|
+
const rootPath = path4.join(config.outputDir, `${lang}.json`);
|
|
409
|
+
fs4.writeFileSync(rootPath, JSON.stringify(rootTree, null, 2) + "\n");
|
|
410
|
+
console.log(`\u2713 ${path4.relative(config.cwd, rootPath)}`);
|
|
411
|
+
for (const mod of scopedModules) {
|
|
412
|
+
const scopedTree = buildScopedTree(registry, lang, SOURCE_LANG, mod.scope);
|
|
413
|
+
if (!scopedTree) continue;
|
|
414
|
+
const scopeDir = path4.join(config.outputDir, scopeToFilesystemPath(mod.scope));
|
|
415
|
+
fs4.mkdirSync(scopeDir, { recursive: true });
|
|
416
|
+
const scopePath = path4.join(scopeDir, `${lang}.json`);
|
|
417
|
+
fs4.writeFileSync(scopePath, JSON.stringify(scopedTree, null, 2) + "\n");
|
|
418
|
+
console.log(`\u2713 ${path4.relative(config.cwd, scopePath)}`);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
console.log(`
|
|
422
|
+
\u{1F4CA} Coverage
|
|
423
|
+
Total keys: ${totalKeys}`);
|
|
424
|
+
for (const lang of config.locales) {
|
|
425
|
+
const translated = translatedByLang[lang];
|
|
426
|
+
const pct = totalKeys > 0 ? Math.round(translated / totalKeys * 100) : 100;
|
|
427
|
+
console.log(`${pct === 100 ? "\u2713" : "\u26A0"} ${lang.toUpperCase()}: ${translated}/${totalKeys} (${pct}%)`);
|
|
428
|
+
const missing = missingByLang[lang];
|
|
429
|
+
if (missing.length && lang !== SOURCE_LANG) {
|
|
430
|
+
console.log(
|
|
431
|
+
` Missing ${missing.length}: ${missing.slice(0, 3).join(", ")}${missing.length > 3 ? `, \u2026 +${missing.length - 3}` : ""}`
|
|
432
|
+
);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
console.log("\n\u2713 Generation complete.\n");
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// projects/hakistack/i18n/cli/scan.ts
|
|
439
|
+
var fs5 = __toESM(require("fs"));
|
|
440
|
+
var path5 = __toESM(require("path"));
|
|
441
|
+
var SUFFIX = ".i18n.ts";
|
|
442
|
+
function collectI18nFiles(dir, out = []) {
|
|
443
|
+
if (!fs5.existsSync(dir)) return out;
|
|
444
|
+
for (const entry of fs5.readdirSync(dir, { withFileTypes: true })) {
|
|
445
|
+
if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
|
|
446
|
+
const full = path5.join(dir, entry.name);
|
|
447
|
+
if (entry.isDirectory()) {
|
|
448
|
+
collectI18nFiles(full, out);
|
|
449
|
+
} else if (entry.isFile() && entry.name.endsWith(SUFFIX)) {
|
|
450
|
+
out.push(full);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return out;
|
|
454
|
+
}
|
|
455
|
+
function extractExports(sourceFile) {
|
|
456
|
+
const content = fs5.readFileSync(sourceFile, "utf-8");
|
|
457
|
+
const pattern = /export\s+const\s+([A-Z][A-Z0-9_]*)\s*=\s*defineTranslations\s*(?:<[^>]*>)?\s*\(\s*(['"])([^'"]+)\2/g;
|
|
458
|
+
const looser = /export\s+const\s+([A-Z][A-Z0-9_]*)\s*=\s*defineTranslations\s*[<(]/g;
|
|
459
|
+
const withScope = /* @__PURE__ */ new Map();
|
|
460
|
+
for (const m of content.matchAll(pattern)) {
|
|
461
|
+
withScope.set(m[1], m[3]);
|
|
462
|
+
}
|
|
463
|
+
const all = [];
|
|
464
|
+
for (const m of content.matchAll(looser)) {
|
|
465
|
+
const name = m[1];
|
|
466
|
+
all.push({ name, scope: withScope.get(name) ?? null });
|
|
467
|
+
}
|
|
468
|
+
return all;
|
|
469
|
+
}
|
|
470
|
+
function toImportPath(sourceFile, definitionsDir) {
|
|
471
|
+
const relative5 = path5.relative(definitionsDir, sourceFile).replace(/\.ts$/, "");
|
|
472
|
+
const posix = relative5.split(path5.sep).join("/");
|
|
473
|
+
return posix.startsWith(".") ? posix : "./" + posix;
|
|
474
|
+
}
|
|
475
|
+
function discover(config) {
|
|
476
|
+
const files = collectI18nFiles(config.srcRoot);
|
|
477
|
+
const modules = [];
|
|
478
|
+
for (const file of files) {
|
|
479
|
+
const importPath = toImportPath(file, config.definitionsDir);
|
|
480
|
+
for (const { name, scope } of extractExports(file)) {
|
|
481
|
+
modules.push({ exportName: name, scope, importPath, sourceFile: file });
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
modules.sort((a, b) => a.exportName.localeCompare(b.exportName));
|
|
485
|
+
return modules;
|
|
486
|
+
}
|
|
487
|
+
function emitBarrel(modules) {
|
|
488
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
489
|
+
for (const mod of modules) {
|
|
490
|
+
if (!byPath.has(mod.importPath)) byPath.set(mod.importPath, []);
|
|
491
|
+
byPath.get(mod.importPath).push(mod.exportName);
|
|
492
|
+
}
|
|
493
|
+
const importEntries = [...byPath.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
494
|
+
const importLines = importEntries.map(([imp, names]) => `import { ${[...names].sort().join(", ")} } from '${imp}';`);
|
|
495
|
+
const reExportLines = importEntries.map(([imp, names]) => `export { ${[...names].sort().join(", ")} } from '${imp}';`);
|
|
496
|
+
const tupleEntries = modules.map((m) => ` ${m.exportName}`).join(",\n");
|
|
497
|
+
return [
|
|
498
|
+
GENERATED_HEADER("index.generated.ts"),
|
|
499
|
+
"",
|
|
500
|
+
...importLines,
|
|
501
|
+
"",
|
|
502
|
+
...reExportLines,
|
|
503
|
+
"",
|
|
504
|
+
"/**",
|
|
505
|
+
" * Tuple of every translation module discovered by the scanner.",
|
|
506
|
+
" * Consumed by the JSON generator and the validator.",
|
|
507
|
+
" */",
|
|
508
|
+
"export const ALL_TRANSLATIONS = [",
|
|
509
|
+
tupleEntries + (tupleEntries ? "," : ""),
|
|
510
|
+
"] as const;",
|
|
511
|
+
""
|
|
512
|
+
].join("\n");
|
|
513
|
+
}
|
|
514
|
+
function newNode() {
|
|
515
|
+
return { refs: [], children: /* @__PURE__ */ new Map() };
|
|
516
|
+
}
|
|
517
|
+
function buildTKTree(modules) {
|
|
518
|
+
const root = newNode();
|
|
519
|
+
const usable = [];
|
|
520
|
+
const byScope = /* @__PURE__ */ new Map();
|
|
521
|
+
for (const mod of modules) {
|
|
522
|
+
if (!mod.scope) continue;
|
|
523
|
+
usable.push(mod);
|
|
524
|
+
(byScope.get(mod.scope) ?? byScope.set(mod.scope, []).get(mod.scope)).push(mod.exportName);
|
|
525
|
+
const parts = mod.scope.split(".");
|
|
526
|
+
let node = root;
|
|
527
|
+
for (const part of parts) {
|
|
528
|
+
if (!node.children.has(part)) node.children.set(part, newNode());
|
|
529
|
+
node = node.children.get(part);
|
|
530
|
+
}
|
|
531
|
+
node.refs.push(mod.exportName);
|
|
532
|
+
}
|
|
533
|
+
const duplicateScopes = new Map([...byScope].filter(([, names]) => names.length > 1));
|
|
534
|
+
return { tree: root, usable, duplicateScopes };
|
|
535
|
+
}
|
|
536
|
+
function serializeTKNode(node, indent) {
|
|
537
|
+
const childIndent = indent + " ";
|
|
538
|
+
const childEntries = [...node.children.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
539
|
+
if (node.refs.length === 1 && childEntries.length === 0) {
|
|
540
|
+
return `${node.refs[0]}.keys`;
|
|
541
|
+
}
|
|
542
|
+
const lines = ["{"];
|
|
543
|
+
for (const ref of node.refs) {
|
|
544
|
+
lines.push(`${childIndent}...${ref}.keys,`);
|
|
545
|
+
}
|
|
546
|
+
for (const [key, child] of childEntries) {
|
|
547
|
+
lines.push(`${childIndent}${key}: ${serializeTKNode(child, childIndent)},`);
|
|
548
|
+
}
|
|
549
|
+
lines.push(`${indent}}`);
|
|
550
|
+
return lines.join("\n");
|
|
551
|
+
}
|
|
552
|
+
function emitKeys(modules) {
|
|
553
|
+
const { tree, usable } = buildTKTree(modules);
|
|
554
|
+
const importNames = [...new Set(usable.map((m) => m.exportName))].sort();
|
|
555
|
+
const importLine = importNames.length ? `import { ${importNames.join(", ")} } from './index.generated';` : "";
|
|
556
|
+
const topEntries = [...tree.children.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
557
|
+
const body = topEntries.map(([key, child]) => ` ${key}: ${serializeTKNode(child, " ")},`).join("\n");
|
|
558
|
+
return [
|
|
559
|
+
GENERATED_HEADER("keys.generated.ts"),
|
|
560
|
+
"",
|
|
561
|
+
importLine,
|
|
562
|
+
"",
|
|
563
|
+
"/**",
|
|
564
|
+
" * Unified translation keys (TK) \u2014 flat camelCase, one mental model.",
|
|
565
|
+
" * `TK.home.welcome` equals the literal key string `'home.welcome'`.",
|
|
566
|
+
" *",
|
|
567
|
+
" * Use in components with `translateSignal(TK.home.welcome)` and in templates",
|
|
568
|
+
" * via the generated typed directive (`{{ t.home.welcome() }}`).",
|
|
569
|
+
" */",
|
|
570
|
+
"export const TK = {",
|
|
571
|
+
body,
|
|
572
|
+
"} as const;",
|
|
573
|
+
"",
|
|
574
|
+
"/** Type of the TK object. */",
|
|
575
|
+
"export type TranslationKeys = typeof TK;",
|
|
576
|
+
""
|
|
577
|
+
].join("\n");
|
|
578
|
+
}
|
|
579
|
+
function emitDirective(config) {
|
|
580
|
+
const sel = config.directiveSelector;
|
|
581
|
+
return [
|
|
582
|
+
GENERATED_HEADER(`${sel}.directive.ts`),
|
|
583
|
+
"",
|
|
584
|
+
`import { Directive, input } from '@angular/core';`,
|
|
585
|
+
`import { TranslateContext, TranslateDirectiveBase } from '${config.packageName}';`,
|
|
586
|
+
"",
|
|
587
|
+
`import { TK } from './keys.generated';`,
|
|
588
|
+
"",
|
|
589
|
+
"/**",
|
|
590
|
+
" * Typed structural translate directive. Extends the library base and pins",
|
|
591
|
+
" * the template context to this project's `typeof TK`, giving full",
|
|
592
|
+
" * autocomplete inside `*" + sel + '="let t"` templates.',
|
|
593
|
+
" */",
|
|
594
|
+
`@Directive({ selector: '[${sel}]' })`,
|
|
595
|
+
`export class ${config.directiveClassName} extends TranslateDirectiveBase {`,
|
|
596
|
+
" /**",
|
|
597
|
+
" * Optional prefix prepended to every key (for scoped translations).",
|
|
598
|
+
` * Microsyntax: \`*${sel}="let t; prefix: 'admin'"\` binds here.`,
|
|
599
|
+
" */",
|
|
600
|
+
` readonly ${sel}Prefix = input<string | undefined>(undefined);`,
|
|
601
|
+
"",
|
|
602
|
+
" protected override prefix(): string | undefined {",
|
|
603
|
+
` return this.${sel}Prefix();`,
|
|
604
|
+
" }",
|
|
605
|
+
"",
|
|
606
|
+
` static ngTemplateContextGuard(_dir: ${config.directiveClassName}, ctx: unknown): ctx is TranslateContext<typeof TK> {`,
|
|
607
|
+
" return true;",
|
|
608
|
+
" }",
|
|
609
|
+
"}",
|
|
610
|
+
""
|
|
611
|
+
].join("\n");
|
|
612
|
+
}
|
|
613
|
+
function GENERATED_HEADER(file) {
|
|
614
|
+
return [
|
|
615
|
+
"/**",
|
|
616
|
+
` * AUTO-GENERATED \u2014 do not edit by hand (${file}).`,
|
|
617
|
+
" *",
|
|
618
|
+
" * Produced by `hakistack-i18n scan`. Re-run the scan after adding,",
|
|
619
|
+
" * removing, or renaming a `*.i18n.ts` module. Safe to gitignore or commit.",
|
|
620
|
+
" */"
|
|
621
|
+
].join("\n");
|
|
622
|
+
}
|
|
623
|
+
function writeIfChanged(file, content) {
|
|
624
|
+
if (fs5.existsSync(file) && fs5.readFileSync(file, "utf-8") === content) return false;
|
|
625
|
+
fs5.mkdirSync(path5.dirname(file), { recursive: true });
|
|
626
|
+
fs5.writeFileSync(file, content, "utf-8");
|
|
627
|
+
return true;
|
|
628
|
+
}
|
|
629
|
+
function runScan(config, opts = {}) {
|
|
630
|
+
const modules = discover(config);
|
|
631
|
+
const log = opts.quiet ? () => {
|
|
632
|
+
} : (m) => console.log(m);
|
|
633
|
+
if (modules.length === 0) {
|
|
634
|
+
console.error(`\u274C No translation modules found under ${config.srcRoot} (expected at least one *.i18n.ts).`);
|
|
635
|
+
if (!opts.listOnly) process.exitCode = 1;
|
|
636
|
+
return { moduleCount: 0, changed: [], missingScopes: [] };
|
|
637
|
+
}
|
|
638
|
+
log(`
|
|
639
|
+
\u{1F50D} i18n scan \u2014 discovered ${modules.length} module${modules.length === 1 ? "" : "s"}:`);
|
|
640
|
+
for (const mod of modules) {
|
|
641
|
+
log(` \u2022 ${mod.exportName}${mod.scope ? ` (${mod.scope})` : ""} \u2190 ${mod.importPath}`);
|
|
642
|
+
}
|
|
643
|
+
const missingScopes = modules.filter((m) => !m.scope).map((m) => m.exportName);
|
|
644
|
+
if (missingScopes.length) {
|
|
645
|
+
console.warn(
|
|
646
|
+
`
|
|
647
|
+
\u26A0\uFE0F Could not statically read the scope for: ${missingScopes.join(", ")}.
|
|
648
|
+
These are excluded from the TK literal. Use a string-literal scope:
|
|
649
|
+
export const X = defineTranslations('scope', { \u2026 }).`
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
const { duplicateScopes } = buildTKTree(modules);
|
|
653
|
+
for (const [scope, names] of duplicateScopes) {
|
|
654
|
+
console.warn(`
|
|
655
|
+
\u26A0\uFE0F Scope '${scope}' is defined by ${names.join(" and ")}; their keys are merged into TK.${scope}.`);
|
|
656
|
+
}
|
|
657
|
+
if (opts.listOnly) {
|
|
658
|
+
log("\n\u2713 Listing only (--list); no files emitted.\n");
|
|
659
|
+
return { moduleCount: modules.length, changed: [], missingScopes };
|
|
660
|
+
}
|
|
661
|
+
const outputs = [
|
|
662
|
+
{ file: path5.join(config.definitionsDir, "index.generated.ts"), content: emitBarrel(modules) },
|
|
663
|
+
{ file: path5.join(config.definitionsDir, "keys.generated.ts"), content: emitKeys(modules) },
|
|
664
|
+
{ file: path5.join(config.definitionsDir, `${config.directiveSelector}.directive.ts`), content: emitDirective(config) }
|
|
665
|
+
];
|
|
666
|
+
const changed = [];
|
|
667
|
+
for (const { file, content } of outputs) {
|
|
668
|
+
if (writeIfChanged(file, content)) changed.push(path5.relative(config.cwd, file));
|
|
669
|
+
}
|
|
670
|
+
if (changed.length) {
|
|
671
|
+
log(`
|
|
672
|
+
\u2713 Wrote:
|
|
673
|
+
${changed.map((f) => ` ${f}`).join("\n")}
|
|
674
|
+
`);
|
|
675
|
+
} else {
|
|
676
|
+
log("\n\u2713 Up to date \u2014 no changes.\n");
|
|
677
|
+
}
|
|
678
|
+
return { moduleCount: modules.length, changed, missingScopes };
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// projects/hakistack/i18n/cli/validate.ts
|
|
682
|
+
function extractPlaceholders(text) {
|
|
683
|
+
return (text.match(/\{\{[^}]+}}/g) || []).sort();
|
|
684
|
+
}
|
|
685
|
+
function arraysEqual(a, b) {
|
|
686
|
+
return a.length === b.length && a.every((v, i) => v === b[i]);
|
|
687
|
+
}
|
|
688
|
+
function validateNode(obj, moduleName, locales, defaultLang, errors, stubs, keyPath = []) {
|
|
689
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
690
|
+
const currentPath = [...keyPath, key];
|
|
691
|
+
const fullKey = currentPath.join(".");
|
|
692
|
+
if (isTranslationValue(value)) {
|
|
693
|
+
const byLang = value;
|
|
694
|
+
const source = byLang[defaultLang];
|
|
695
|
+
if (!source || source.trim() === "") {
|
|
696
|
+
errors.push({
|
|
697
|
+
module: moduleName,
|
|
698
|
+
key: fullKey,
|
|
699
|
+
language: defaultLang,
|
|
700
|
+
issue: `Missing or empty required ${defaultLang} translation`,
|
|
701
|
+
severity: "error"
|
|
702
|
+
});
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
const srcPlaceholders = extractPlaceholders(source);
|
|
706
|
+
const srcHasPlaceholders = srcPlaceholders.length > 0;
|
|
707
|
+
let hasAnyOtherLocale = false;
|
|
708
|
+
for (const lang of locales) {
|
|
709
|
+
if (lang === defaultLang) continue;
|
|
710
|
+
const translation = byLang[lang];
|
|
711
|
+
if (!translation) {
|
|
712
|
+
errors.push({
|
|
713
|
+
module: moduleName,
|
|
714
|
+
key: fullKey,
|
|
715
|
+
language: lang,
|
|
716
|
+
issue: srcHasPlaceholders ? `Missing translation for placeholder string. Strings containing {{\u2026}} require parity in every locale.` : "Missing translation (will fallback)",
|
|
717
|
+
severity: srcHasPlaceholders ? "error" : "warning"
|
|
718
|
+
});
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
hasAnyOtherLocale = true;
|
|
722
|
+
if (translation.trim() === "") {
|
|
723
|
+
errors.push({ module: moduleName, key: fullKey, language: lang, issue: "Empty translation value", severity: "error" });
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
const langPlaceholders = extractPlaceholders(translation);
|
|
727
|
+
if (!arraysEqual(srcPlaceholders, langPlaceholders)) {
|
|
728
|
+
errors.push({
|
|
729
|
+
module: moduleName,
|
|
730
|
+
key: fullKey,
|
|
731
|
+
language: lang,
|
|
732
|
+
issue: `Placeholder mismatch. ${defaultLang.toUpperCase()}: [${srcPlaceholders.join(", ")}] | ${lang.toUpperCase()}: [${langPlaceholders.join(", ")}]`,
|
|
733
|
+
severity: "error"
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
if (!hasAnyOtherLocale && locales.length > 1) {
|
|
738
|
+
stubs.push({ module: moduleName, key: fullKey });
|
|
739
|
+
}
|
|
740
|
+
} else if (typeof value === "object" && value !== null) {
|
|
741
|
+
validateNode(value, moduleName, locales, defaultLang, errors, stubs, currentPath);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
async function runValidate(config) {
|
|
746
|
+
console.log("\n\u{1F50D} i18n validation\n" + "=".repeat(50));
|
|
747
|
+
const registry = await loadRegistry(config);
|
|
748
|
+
const errors = [];
|
|
749
|
+
const stubs = [];
|
|
750
|
+
for (const mod of registry) {
|
|
751
|
+
validateNode(mod.translations, mod.scope, config.locales, SOURCE_LANG, errors, stubs);
|
|
752
|
+
}
|
|
753
|
+
const actualErrors = errors.filter((e) => e.severity === "error");
|
|
754
|
+
const warnings = errors.filter((e) => e.severity === "warning");
|
|
755
|
+
if (actualErrors.length === 0 && warnings.length === 0 && stubs.length === 0) {
|
|
756
|
+
console.log("\n\u2713 All translations are valid!\n");
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (actualErrors.length) {
|
|
760
|
+
console.log(`
|
|
761
|
+
\u274C ${actualErrors.length} error(s):
|
|
762
|
+
`);
|
|
763
|
+
for (const e of actualErrors) {
|
|
764
|
+
console.log(` [${e.module}] ${e.key} (${e.language.toUpperCase()})
|
|
765
|
+
\u2192 ${e.issue}`);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if (warnings.length) {
|
|
769
|
+
console.log(`
|
|
770
|
+
\u26A0\uFE0F ${warnings.length} warning(s):
|
|
771
|
+
`);
|
|
772
|
+
const byLang = {};
|
|
773
|
+
for (const w of warnings) (byLang[w.language] ??= []).push(w);
|
|
774
|
+
for (const [lang, list] of Object.entries(byLang)) {
|
|
775
|
+
console.log(` ${lang.toUpperCase()}: ${list.length} missing`);
|
|
776
|
+
for (const w of list.slice(0, 5)) console.log(` - ${w.key}`);
|
|
777
|
+
if (list.length > 5) console.log(` \u2026 and ${list.length - 5} more`);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
if (stubs.length) {
|
|
781
|
+
console.log(`
|
|
782
|
+
\u{1F4DD} Stub report \u2014 ${stubs.length} source-only ${stubs.length === 1 ? "leaf" : "leaves"}:
|
|
783
|
+
`);
|
|
784
|
+
const byModule = {};
|
|
785
|
+
for (const s of stubs) (byModule[s.module] ??= []).push(s.key);
|
|
786
|
+
for (const [moduleName, keys] of Object.entries(byModule)) {
|
|
787
|
+
console.log(` ${moduleName}: ${keys.length}`);
|
|
788
|
+
for (const k of keys.slice(0, 5)) console.log(` - ${k}`);
|
|
789
|
+
if (keys.length > 5) console.log(` \u2026 and ${keys.length - 5} more`);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
console.log(`
|
|
793
|
+
\u{1F4CA} Summary
|
|
794
|
+
Errors: ${actualErrors.length} Warnings: ${warnings.length} Stubs: ${stubs.length}`);
|
|
795
|
+
if (actualErrors.length) {
|
|
796
|
+
console.log("\n\u274C Validation failed!\n");
|
|
797
|
+
process.exitCode = 1;
|
|
798
|
+
} else {
|
|
799
|
+
console.log("\n\u2713 Validation passed.\n");
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
// projects/hakistack/i18n/cli/watch.ts
|
|
804
|
+
var path6 = __toESM(require("path"));
|
|
805
|
+
var import_jiti3 = require("jiti");
|
|
806
|
+
var SUFFIX2 = ".i18n.ts";
|
|
807
|
+
async function runWatch(config) {
|
|
808
|
+
let chokidar;
|
|
809
|
+
try {
|
|
810
|
+
const mod = await (0, import_jiti3.createJiti)(__filename).import("chokidar");
|
|
811
|
+
chokidar = mod.default ?? mod;
|
|
812
|
+
} catch {
|
|
813
|
+
console.error('i18n watch requires the optional dependency "chokidar". Install it with:\n npm i -D chokidar');
|
|
814
|
+
process.exitCode = 1;
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
runScan(config, { quiet: true });
|
|
818
|
+
console.log(`[i18n-watch] watching ${path6.relative(config.cwd, config.srcRoot)}/**/*${SUFFIX2}`);
|
|
819
|
+
let running = false;
|
|
820
|
+
let pending = false;
|
|
821
|
+
const trigger = (label) => {
|
|
822
|
+
if (running) {
|
|
823
|
+
pending = true;
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
running = true;
|
|
827
|
+
console.log(`[i18n-watch] ${label} \u2014 scanning`);
|
|
828
|
+
try {
|
|
829
|
+
runScan(config, { quiet: true });
|
|
830
|
+
} finally {
|
|
831
|
+
running = false;
|
|
832
|
+
if (pending) {
|
|
833
|
+
pending = false;
|
|
834
|
+
trigger("coalesced");
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
const watcher = chokidar.watch(config.srcRoot, {
|
|
839
|
+
ignoreInitial: true,
|
|
840
|
+
awaitWriteFinish: { stabilityThreshold: 150, pollInterval: 30 },
|
|
841
|
+
ignored: (p, stats) => {
|
|
842
|
+
const base = path6.basename(p);
|
|
843
|
+
if (base === "node_modules" || base.startsWith(".")) return true;
|
|
844
|
+
if (stats?.isFile()) return !p.endsWith(SUFFIX2);
|
|
845
|
+
return false;
|
|
846
|
+
}
|
|
847
|
+
});
|
|
848
|
+
watcher.on("add", (p) => trigger(`add ${path6.relative(config.cwd, p)}`)).on("unlink", (p) => trigger(`remove ${path6.relative(config.cwd, p)}`)).on("change", (p) => trigger(`change ${path6.relative(config.cwd, p)}`));
|
|
849
|
+
const shutdown = () => watcher.close().then(() => process.exit(0));
|
|
850
|
+
process.on("SIGINT", shutdown);
|
|
851
|
+
process.on("SIGTERM", shutdown);
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// projects/hakistack/i18n/cli/bin.ts
|
|
855
|
+
function parseArgs(argv) {
|
|
856
|
+
const command = argv[0] ?? "help";
|
|
857
|
+
const flags = {};
|
|
858
|
+
for (let i = 1; i < argv.length; i++) {
|
|
859
|
+
const arg = argv[i];
|
|
860
|
+
if (!arg.startsWith("--")) continue;
|
|
861
|
+
const key = arg.slice(2);
|
|
862
|
+
const next = argv[i + 1];
|
|
863
|
+
if (next !== void 0 && !next.startsWith("--")) {
|
|
864
|
+
flags[key] = next;
|
|
865
|
+
i++;
|
|
866
|
+
} else {
|
|
867
|
+
flags[key] = true;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
return { command, flags };
|
|
871
|
+
}
|
|
872
|
+
function configOverrides(flags) {
|
|
873
|
+
const o = {};
|
|
874
|
+
if (typeof flags["src-root"] === "string") o.srcRoot = flags["src-root"];
|
|
875
|
+
if (typeof flags["definitions-dir"] === "string") o.definitionsDir = flags["definitions-dir"];
|
|
876
|
+
if (typeof flags["output-dir"] === "string") o.outputDir = flags["output-dir"];
|
|
877
|
+
if (typeof flags["locales"] === "string")
|
|
878
|
+
o.locales = flags["locales"].split(",").map((s) => s.trim()).filter(Boolean);
|
|
879
|
+
return o;
|
|
880
|
+
}
|
|
881
|
+
var HELP = `hakistack-i18n \u2014 type-safe i18n codegen
|
|
882
|
+
|
|
883
|
+
Usage: hakistack-i18n <command> [flags]
|
|
884
|
+
|
|
885
|
+
Commands:
|
|
886
|
+
scan Discover *.i18n.ts and emit barrel + TK literal + typed directive
|
|
887
|
+
generate Write JSON translation files
|
|
888
|
+
validate Gate on missing / placeholder-mismatched translations
|
|
889
|
+
find-unused Report defined keys with no references
|
|
890
|
+
watch Re-run scan on *.i18n.ts changes
|
|
891
|
+
|
|
892
|
+
Flags:
|
|
893
|
+
--config <path> Explicit config file
|
|
894
|
+
--src-root <dir> Directory scanned for *.i18n.ts
|
|
895
|
+
--definitions-dir <d> Where generated files land
|
|
896
|
+
--output-dir <dir> JSON output directory
|
|
897
|
+
--locales <a,b,c> Comma-separated locale ids (en is always included)
|
|
898
|
+
--list (scan) list modules without emitting
|
|
899
|
+
--strict (find-unused) exit 1 if unused keys exist
|
|
900
|
+
--verbose (find-unused) print reference locations
|
|
901
|
+
`;
|
|
902
|
+
async function main() {
|
|
903
|
+
const { command, flags } = parseArgs(process.argv.slice(2));
|
|
904
|
+
if (command === "help" || command === "--help" || command === "-h") {
|
|
905
|
+
console.log(HELP);
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
const cwd = process.cwd();
|
|
909
|
+
const overrides = configOverrides(flags);
|
|
910
|
+
if (typeof flags["config"] === "string") {
|
|
911
|
+
process.chdir(path7.dirname(path7.resolve(cwd, flags["config"])));
|
|
912
|
+
}
|
|
913
|
+
const config = await loadConfig(process.cwd(), overrides);
|
|
914
|
+
switch (command) {
|
|
915
|
+
case "scan":
|
|
916
|
+
runScan(config, { listOnly: flags["list"] === true });
|
|
917
|
+
break;
|
|
918
|
+
case "generate":
|
|
919
|
+
await runGenerate(config);
|
|
920
|
+
break;
|
|
921
|
+
case "validate":
|
|
922
|
+
await runValidate(config);
|
|
923
|
+
break;
|
|
924
|
+
case "find-unused":
|
|
925
|
+
await runFindUnused(config, { strict: flags["strict"] === true, verbose: flags["verbose"] === true });
|
|
926
|
+
break;
|
|
927
|
+
case "watch":
|
|
928
|
+
await runWatch(config);
|
|
929
|
+
break;
|
|
930
|
+
default:
|
|
931
|
+
console.error(`Unknown command: ${command}
|
|
932
|
+
`);
|
|
933
|
+
console.log(HELP);
|
|
934
|
+
process.exitCode = 1;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
main().catch((err) => {
|
|
938
|
+
console.error(err instanceof Error ? err.message : err);
|
|
939
|
+
process.exitCode = 1;
|
|
940
|
+
});
|