@puzzle-ui/i18n 0.0.0-stage → 0.16.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/README.md +94 -2
- package/ai/instructions.md +141 -0
- package/ai/manifest.json +10 -0
- package/dist/LICENSE +21 -0
- package/dist/_virtual/_rolldown/runtime.cjs +22 -0
- package/dist/adapters/next.cjs +11 -0
- package/dist/adapters/next.cjs.map +1 -0
- package/dist/adapters/next.d.cts +7 -0
- package/dist/adapters/next.d.ts +7 -0
- package/dist/adapters/next.js +10 -0
- package/dist/adapters/next.js.map +1 -0
- package/dist/adapters/react-router.cjs +13 -0
- package/dist/adapters/react-router.cjs.map +1 -0
- package/dist/adapters/react-router.d.cts +10 -0
- package/dist/adapters/react-router.d.ts +10 -0
- package/dist/adapters/react-router.js +12 -0
- package/dist/adapters/react-router.js.map +1 -0
- package/dist/adapters/request.cjs +67 -0
- package/dist/adapters/request.cjs.map +1 -0
- package/dist/adapters/request.d.cts +16 -0
- package/dist/adapters/request.d.ts +16 -0
- package/dist/adapters/request.js +65 -0
- package/dist/adapters/request.js.map +1 -0
- package/dist/adapters/tanstack.cjs +13 -0
- package/dist/adapters/tanstack.cjs.map +1 -0
- package/dist/adapters/tanstack.d.cts +10 -0
- package/dist/adapters/tanstack.d.ts +10 -0
- package/dist/adapters/tanstack.js +12 -0
- package/dist/adapters/tanstack.js.map +1 -0
- package/dist/ai/index.cjs +205 -0
- package/dist/ai/index.cjs.map +1 -0
- package/dist/ai/index.d.cts +75 -0
- package/dist/ai/index.d.ts +75 -0
- package/dist/ai/index.js +195 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/ai/review.cjs +319 -0
- package/dist/ai/review.cjs.map +1 -0
- package/dist/ai/review.d.cts +91 -0
- package/dist/ai/review.d.ts +91 -0
- package/dist/ai/review.js +315 -0
- package/dist/ai/review.js.map +1 -0
- package/dist/cli/bin.cjs +10 -0
- package/dist/cli/bin.cjs.map +1 -0
- package/dist/cli/bin.d.cts +1 -0
- package/dist/cli/bin.d.ts +1 -0
- package/dist/cli/bin.js +12 -0
- package/dist/cli/bin.js.map +1 -0
- package/dist/cli/index.cjs +310 -0
- package/dist/cli/index.cjs.map +1 -0
- package/dist/cli/index.d.cts +7 -0
- package/dist/cli/index.d.ts +7 -0
- package/dist/cli/index.js +309 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/compiler/index.cjs +218 -0
- package/dist/compiler/index.cjs.map +1 -0
- package/dist/compiler/index.d.cts +18 -0
- package/dist/compiler/index.d.ts +18 -0
- package/dist/compiler/index.js +210 -0
- package/dist/compiler/index.js.map +1 -0
- package/dist/compiler/typescript.cjs +251 -0
- package/dist/compiler/typescript.cjs.map +1 -0
- package/dist/compiler/typescript.d.cts +27 -0
- package/dist/compiler/typescript.d.ts +27 -0
- package/dist/compiler/typescript.js +247 -0
- package/dist/compiler/typescript.js.map +1 -0
- package/dist/compiler/vite.cjs +94 -0
- package/dist/compiler/vite.cjs.map +1 -0
- package/dist/compiler/vite.d.cts +13 -0
- package/dist/compiler/vite.d.ts +13 -0
- package/dist/compiler/vite.js +92 -0
- package/dist/compiler/vite.js.map +1 -0
- package/dist/content/index.cjs +156 -0
- package/dist/content/index.cjs.map +1 -0
- package/dist/content/index.d.cts +75 -0
- package/dist/content/index.d.ts +75 -0
- package/dist/content/index.js +151 -0
- package/dist/content/index.js.map +1 -0
- package/dist/content/sanity.cjs +74 -0
- package/dist/content/sanity.cjs.map +1 -0
- package/dist/content/sanity.d.cts +19 -0
- package/dist/content/sanity.d.ts +19 -0
- package/dist/content/sanity.js +73 -0
- package/dist/content/sanity.js.map +1 -0
- package/dist/devtools/index.cjs +77 -0
- package/dist/devtools/index.cjs.map +1 -0
- package/dist/devtools/index.d.cts +29 -0
- package/dist/devtools/index.d.ts +29 -0
- package/dist/devtools/index.js +75 -0
- package/dist/devtools/index.js.map +1 -0
- package/dist/format.cjs +17 -0
- package/dist/format.cjs.map +1 -0
- package/dist/format.d.cts +9 -0
- package/dist/format.d.ts +9 -0
- package/dist/format.js +13 -0
- package/dist/format.js.map +1 -0
- package/dist/index.cjs +20 -0
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/locale.cjs +158 -0
- package/dist/locale.cjs.map +1 -0
- package/dist/locale.d.cts +42 -0
- package/dist/locale.d.ts +42 -0
- package/dist/locale.js +155 -0
- package/dist/locale.js.map +1 -0
- package/dist/react/index.cjs +239 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +105 -0
- package/dist/react/index.d.ts +105 -0
- package/dist/react/index.js +238 -0
- package/dist/react/index.js.map +1 -0
- package/dist/routing/index.cjs +381 -0
- package/dist/routing/index.cjs.map +1 -0
- package/dist/routing/index.d.cts +44 -0
- package/dist/routing/index.d.ts +44 -0
- package/dist/routing/index.js +380 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/runtime.cjs +261 -0
- package/dist/runtime.cjs.map +1 -0
- package/dist/runtime.d.cts +74 -0
- package/dist/runtime.d.ts +74 -0
- package/dist/runtime.js +257 -0
- package/dist/runtime.js.map +1 -0
- package/dist/seo/index.cjs +212 -0
- package/dist/seo/index.cjs.map +1 -0
- package/dist/seo/index.d.cts +52 -0
- package/dist/seo/index.d.ts +52 -0
- package/dist/seo/index.js +209 -0
- package/dist/seo/index.js.map +1 -0
- package/dist/seo/origin.cjs +27 -0
- package/dist/seo/origin.cjs.map +1 -0
- package/dist/seo/origin.js +26 -0
- package/dist/seo/origin.js.map +1 -0
- package/dist/seo/sitemap.cjs +74 -0
- package/dist/seo/sitemap.cjs.map +1 -0
- package/dist/seo/sitemap.d.cts +16 -0
- package/dist/seo/sitemap.d.ts +16 -0
- package/dist/seo/sitemap.js +72 -0
- package/dist/seo/sitemap.js.map +1 -0
- package/dist/sources/index.cjs +227 -0
- package/dist/sources/index.cjs.map +1 -0
- package/dist/sources/index.d.cts +41 -0
- package/dist/sources/index.d.ts +41 -0
- package/dist/sources/index.js +222 -0
- package/dist/sources/index.js.map +1 -0
- package/dist/sources/node.cjs +50 -0
- package/dist/sources/node.cjs.map +1 -0
- package/dist/sources/node.d.cts +5 -0
- package/dist/sources/node.d.ts +5 -0
- package/dist/sources/node.js +49 -0
- package/dist/sources/node.js.map +1 -0
- package/package.json +256 -4
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import * as ts from "typescript";
|
|
2
|
+
// src/compiler/typescript.ts
|
|
3
|
+
const getCalleeName = (expression) => {
|
|
4
|
+
if (ts.isIdentifier(expression)) return expression.text;
|
|
5
|
+
if (ts.isPropertyAccessExpression(expression)) return expression.name.text;
|
|
6
|
+
if (ts.isElementAccessExpression(expression) && expression.argumentExpression && ts.isStringLiteralLike(expression.argumentExpression)) return expression.argumentExpression.text;
|
|
7
|
+
};
|
|
8
|
+
const getStaticKey = (expression) => {
|
|
9
|
+
if (expression && (ts.isStringLiteralLike(expression) || ts.isNoSubstitutionTemplateLiteral(expression))) return expression.text;
|
|
10
|
+
};
|
|
11
|
+
const getScriptKind = (fileName) => fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : fileName.endsWith(".jsx") ? ts.ScriptKind.JSX : ts.ScriptKind.TS;
|
|
12
|
+
const analyzeSource = (source, options) => {
|
|
13
|
+
const fileName = options.fileName ?? "source.ts";
|
|
14
|
+
const sourceFile = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, getScriptKind(fileName));
|
|
15
|
+
const callees = new Set(options.callees ?? ["t", "translate"]);
|
|
16
|
+
const keys = /* @__PURE__ */ new Set();
|
|
17
|
+
const calls = [];
|
|
18
|
+
const diagnostics = [];
|
|
19
|
+
const parseDiagnostics = sourceFile.parseDiagnostics ?? [];
|
|
20
|
+
for (const diagnostic of parseDiagnostics) {
|
|
21
|
+
const position = diagnostic.start ?? 0;
|
|
22
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(position);
|
|
23
|
+
diagnostics.push({
|
|
24
|
+
code: "syntax-error",
|
|
25
|
+
file: fileName,
|
|
26
|
+
line: line + 1,
|
|
27
|
+
column: character + 1,
|
|
28
|
+
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const visit = (node) => {
|
|
32
|
+
if (ts.isCallExpression(node) && callees.has(getCalleeName(node.expression) ?? "")) {
|
|
33
|
+
const keyExpression = node.arguments[0];
|
|
34
|
+
const key = getStaticKey(keyExpression);
|
|
35
|
+
if (key !== void 0 && keyExpression) {
|
|
36
|
+
keys.add(key);
|
|
37
|
+
calls.push({
|
|
38
|
+
key,
|
|
39
|
+
keyExpression
|
|
40
|
+
});
|
|
41
|
+
} else if (keyExpression) {
|
|
42
|
+
const { line, character } = sourceFile.getLineAndCharacterOfPosition(keyExpression.getStart(sourceFile));
|
|
43
|
+
diagnostics.push({
|
|
44
|
+
code: "dynamic-key",
|
|
45
|
+
file: fileName,
|
|
46
|
+
line: line + 1,
|
|
47
|
+
column: character + 1,
|
|
48
|
+
message: "Translation keys must be string literals for reliable catalog scanning."
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
ts.forEachChild(node, visit);
|
|
53
|
+
};
|
|
54
|
+
visit(sourceFile);
|
|
55
|
+
return {
|
|
56
|
+
sourceFile,
|
|
57
|
+
keys: Object.freeze([...keys].sort()),
|
|
58
|
+
calls: Object.freeze(calls),
|
|
59
|
+
diagnostics: Object.freeze(diagnostics)
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
const encodeVlq = (value) => {
|
|
63
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
64
|
+
let encoded = "";
|
|
65
|
+
let vlq = value < 0 ? -value << 1 | 1 : value << 1;
|
|
66
|
+
do {
|
|
67
|
+
let digit = vlq & 31;
|
|
68
|
+
vlq >>>= 5;
|
|
69
|
+
if (vlq > 0) digit |= 32;
|
|
70
|
+
encoded += alphabet[digit];
|
|
71
|
+
} while (vlq > 0);
|
|
72
|
+
return encoded;
|
|
73
|
+
};
|
|
74
|
+
const getLineStarts = (source) => {
|
|
75
|
+
const starts = [0];
|
|
76
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
77
|
+
const character = source[index];
|
|
78
|
+
if (character === "\r") {
|
|
79
|
+
if (source[index + 1] === "\n") index += 1;
|
|
80
|
+
starts.push(index + 1);
|
|
81
|
+
} else if (character === "\n" || character === "\u2028" || character === "\u2029") starts.push(index + 1);
|
|
82
|
+
}
|
|
83
|
+
return starts;
|
|
84
|
+
};
|
|
85
|
+
const getLineAndColumn = (lineStarts, position) => {
|
|
86
|
+
let low = 0;
|
|
87
|
+
let high = lineStarts.length;
|
|
88
|
+
while (low < high) {
|
|
89
|
+
const middle = Math.floor((low + high) / 2);
|
|
90
|
+
if ((lineStarts[middle] ?? 0) <= position) low = middle + 1;
|
|
91
|
+
else high = middle;
|
|
92
|
+
}
|
|
93
|
+
const line = Math.max(0, low - 1);
|
|
94
|
+
return {
|
|
95
|
+
line,
|
|
96
|
+
column: position - (lineStarts[line] ?? 0)
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
const createSourceMap = (fileName, source, code, edits) => {
|
|
100
|
+
const sourceLineStarts = getLineStarts(source);
|
|
101
|
+
const outputLineStarts = getLineStarts(code);
|
|
102
|
+
const segmentsByLine = /* @__PURE__ */ new Map();
|
|
103
|
+
const addAnchor = (generatedPosition, originalPosition) => {
|
|
104
|
+
const generated = getLineAndColumn(outputLineStarts, generatedPosition);
|
|
105
|
+
const original = getLineAndColumn(sourceLineStarts, originalPosition);
|
|
106
|
+
let segments = segmentsByLine.get(generated.line);
|
|
107
|
+
if (!segments) {
|
|
108
|
+
segments = /* @__PURE__ */ new Map();
|
|
109
|
+
segmentsByLine.set(generated.line, segments);
|
|
110
|
+
}
|
|
111
|
+
segments.set(generated.column, {
|
|
112
|
+
source: 0,
|
|
113
|
+
originalLine: original.line,
|
|
114
|
+
originalColumn: original.column
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
for (let line = 0; line < outputLineStarts.length; line += 1) addAnchor(outputLineStarts[line] ?? code.length, sourceLineStarts[line] ?? source.length);
|
|
118
|
+
for (const edit of edits) {
|
|
119
|
+
addAnchor(edit.outputStart, edit.start);
|
|
120
|
+
addAnchor(edit.outputEnd, edit.end);
|
|
121
|
+
}
|
|
122
|
+
const mapOutputPosition = (position) => {
|
|
123
|
+
let offset = 0;
|
|
124
|
+
for (const edit of edits) {
|
|
125
|
+
if (position < edit.outputStart) return position - offset;
|
|
126
|
+
if (position <= edit.outputEnd) return position === edit.outputEnd ? edit.end : edit.start;
|
|
127
|
+
offset += edit.replacement.length - (edit.end - edit.start);
|
|
128
|
+
}
|
|
129
|
+
return position - offset;
|
|
130
|
+
};
|
|
131
|
+
const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, fileName.endsWith(".tsx") || fileName.endsWith(".jsx") ? ts.LanguageVariant.JSX : ts.LanguageVariant.Standard, code);
|
|
132
|
+
let token = scanner.scan();
|
|
133
|
+
while (token !== ts.SyntaxKind.EndOfFileToken) {
|
|
134
|
+
addAnchor(scanner.getTokenPos(), mapOutputPosition(scanner.getTokenPos()));
|
|
135
|
+
addAnchor(scanner.getTextPos(), mapOutputPosition(scanner.getTextPos()));
|
|
136
|
+
token = scanner.scan();
|
|
137
|
+
}
|
|
138
|
+
let previousSource = 0;
|
|
139
|
+
let previousOriginalLine = 0;
|
|
140
|
+
let previousOriginalColumn = 0;
|
|
141
|
+
const mappings = outputLineStarts.map((_, line) => {
|
|
142
|
+
const segments = [...segmentsByLine.get(line)?.entries() ?? []].sort(([left], [right]) => left - right);
|
|
143
|
+
let previousGeneratedColumn = 0;
|
|
144
|
+
return segments.map(([generatedColumn, mapping]) => {
|
|
145
|
+
const encoded = [
|
|
146
|
+
encodeVlq(generatedColumn - previousGeneratedColumn),
|
|
147
|
+
encodeVlq(mapping.source - previousSource),
|
|
148
|
+
encodeVlq(mapping.originalLine - previousOriginalLine),
|
|
149
|
+
encodeVlq(mapping.originalColumn - previousOriginalColumn)
|
|
150
|
+
].join("");
|
|
151
|
+
previousGeneratedColumn = generatedColumn;
|
|
152
|
+
previousSource = mapping.source;
|
|
153
|
+
previousOriginalLine = mapping.originalLine;
|
|
154
|
+
previousOriginalColumn = mapping.originalColumn;
|
|
155
|
+
return encoded;
|
|
156
|
+
}).join(",");
|
|
157
|
+
});
|
|
158
|
+
return JSON.stringify({
|
|
159
|
+
version: 3,
|
|
160
|
+
file: fileName,
|
|
161
|
+
sources: [fileName],
|
|
162
|
+
sourcesContent: [source],
|
|
163
|
+
names: [],
|
|
164
|
+
mappings: mappings.join(";")
|
|
165
|
+
});
|
|
166
|
+
};
|
|
167
|
+
const toStringLiteral = (value) => JSON.stringify(value).replace(/[\u2028\u2029]/g, (character) => {
|
|
168
|
+
return `\\u${character.charCodeAt(0).toString(16)}`;
|
|
169
|
+
});
|
|
170
|
+
const extractTranslationKeys = (source, options = {}) => {
|
|
171
|
+
const result = analyzeSource(source, options);
|
|
172
|
+
return {
|
|
173
|
+
keys: result.keys,
|
|
174
|
+
diagnostics: result.diagnostics
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
const transformTranslationKeys = (source, options) => {
|
|
178
|
+
const fileName = options.fileName ?? "source.ts";
|
|
179
|
+
const analysis = analyzeSource(source, options);
|
|
180
|
+
const diagnostics = [...analysis.diagnostics];
|
|
181
|
+
const edits = [];
|
|
182
|
+
if (!diagnostics.some((diagnostic) => diagnostic.code === "syntax-error")) for (const { key, keyExpression } of analysis.calls) {
|
|
183
|
+
if (!Object.hasOwn(options.replacements, key)) continue;
|
|
184
|
+
const replacement = options.replacements[key];
|
|
185
|
+
if (typeof replacement !== "string") {
|
|
186
|
+
const { line, character } = analysis.sourceFile.getLineAndCharacterOfPosition(keyExpression.getStart(analysis.sourceFile));
|
|
187
|
+
diagnostics.push({
|
|
188
|
+
code: "invalid-replacement",
|
|
189
|
+
file: fileName,
|
|
190
|
+
line: line + 1,
|
|
191
|
+
column: character + 1,
|
|
192
|
+
key,
|
|
193
|
+
message: `Replacement for "${key}" must be a string.`
|
|
194
|
+
});
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (replacement !== key) edits.push({
|
|
198
|
+
start: keyExpression.getStart(analysis.sourceFile),
|
|
199
|
+
end: keyExpression.getEnd(),
|
|
200
|
+
replacement: toStringLiteral(replacement)
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
edits.sort((left, right) => left.start - right.start || left.end - right.end);
|
|
204
|
+
for (let index = 1; index < edits.length; index += 1) {
|
|
205
|
+
const previous = edits[index - 1];
|
|
206
|
+
const current = edits[index];
|
|
207
|
+
if (previous && current && current.start < previous.end) {
|
|
208
|
+
const { line, character } = analysis.sourceFile.getLineAndCharacterOfPosition(current.start);
|
|
209
|
+
diagnostics.push({
|
|
210
|
+
code: "overlapping-replacement",
|
|
211
|
+
file: fileName,
|
|
212
|
+
line: line + 1,
|
|
213
|
+
column: character + 1,
|
|
214
|
+
message: "Overlapping translation-key replacements were rejected; source was left unchanged."
|
|
215
|
+
});
|
|
216
|
+
return {
|
|
217
|
+
code: source,
|
|
218
|
+
map: options.sourceMap === false ? null : createSourceMap(fileName, source, source, []),
|
|
219
|
+
diagnostics: Object.freeze(diagnostics)
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
let code = "";
|
|
224
|
+
let sourceOffset = 0;
|
|
225
|
+
const appliedEdits = [];
|
|
226
|
+
for (const edit of edits) {
|
|
227
|
+
code += source.slice(sourceOffset, edit.start);
|
|
228
|
+
const outputStart = code.length;
|
|
229
|
+
code += edit.replacement;
|
|
230
|
+
const outputEnd = code.length;
|
|
231
|
+
appliedEdits.push({
|
|
232
|
+
...edit,
|
|
233
|
+
outputStart,
|
|
234
|
+
outputEnd
|
|
235
|
+
});
|
|
236
|
+
sourceOffset = edit.end;
|
|
237
|
+
}
|
|
238
|
+
code += source.slice(sourceOffset);
|
|
239
|
+
return {
|
|
240
|
+
code,
|
|
241
|
+
map: options.sourceMap === false ? null : createSourceMap(fileName, source, code, appliedEdits),
|
|
242
|
+
diagnostics: Object.freeze(diagnostics)
|
|
243
|
+
};
|
|
244
|
+
};
|
|
245
|
+
export { extractTranslationKeys, transformTranslationKeys };
|
|
246
|
+
|
|
247
|
+
//# sourceMappingURL=typescript.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typescript.js","names":[],"sources":["../../src/compiler/typescript.ts"],"sourcesContent":["import * as ts from \"typescript\";\n\nexport interface ExtractTranslationKeysOptions {\n fileName?: string;\n callees?: readonly string[];\n}\n\nexport interface TranslationSourceDiagnostic {\n code:\n | \"dynamic-key\"\n | \"syntax-error\"\n | \"invalid-replacement\"\n | \"overlapping-replacement\";\n file: string;\n line: number;\n column: number;\n key?: string;\n message: string;\n}\n\nexport interface ExtractedTranslationKeys {\n keys: readonly string[];\n diagnostics: readonly TranslationSourceDiagnostic[];\n}\n\nexport interface TransformTranslationKeysOptions\n extends ExtractTranslationKeysOptions {\n replacements: Readonly<Record<string, string>>;\n sourceMap?: boolean;\n}\n\nexport interface TransformTranslationKeysResult {\n code: string;\n map: string | null;\n diagnostics: readonly TranslationSourceDiagnostic[];\n}\n\ninterface TranslationCall {\n key: string;\n keyExpression: ts.Expression;\n}\n\ninterface SourceAnalysis extends ExtractedTranslationKeys {\n sourceFile: ts.SourceFile;\n calls: readonly TranslationCall[];\n}\n\ninterface TextEdit {\n start: number;\n end: number;\n replacement: string;\n}\n\ninterface AppliedEdit extends TextEdit {\n outputStart: number;\n outputEnd: number;\n}\n\nconst getCalleeName = (expression: ts.Expression): string | undefined => {\n if (ts.isIdentifier(expression)) {\n return expression.text;\n }\n\n if (ts.isPropertyAccessExpression(expression)) {\n return expression.name.text;\n }\n\n if (\n ts.isElementAccessExpression(expression) &&\n expression.argumentExpression &&\n ts.isStringLiteralLike(expression.argumentExpression)\n ) {\n return expression.argumentExpression.text;\n }\n\n return undefined;\n};\n\nconst getStaticKey = (expression: ts.Expression | undefined): string | undefined => {\n if (\n expression &&\n (ts.isStringLiteralLike(expression) ||\n ts.isNoSubstitutionTemplateLiteral(expression))\n ) {\n return expression.text;\n }\n\n return undefined;\n};\n\nconst getScriptKind = (fileName: string): ts.ScriptKind =>\n fileName.endsWith(\".tsx\")\n ? ts.ScriptKind.TSX\n : fileName.endsWith(\".jsx\")\n ? ts.ScriptKind.JSX\n : ts.ScriptKind.TS;\n\nconst analyzeSource = (\n source: string,\n options: ExtractTranslationKeysOptions,\n): SourceAnalysis => {\n const fileName = options.fileName ?? \"source.ts\";\n const sourceFile = ts.createSourceFile(\n fileName,\n source,\n ts.ScriptTarget.Latest,\n true,\n getScriptKind(fileName),\n );\n const callees = new Set(options.callees ?? [\"t\", \"translate\"]);\n const keys = new Set<string>();\n const calls: TranslationCall[] = [];\n const diagnostics: TranslationSourceDiagnostic[] = [];\n const parseDiagnostics = (\n sourceFile as ts.SourceFile & { parseDiagnostics?: readonly ts.Diagnostic[] }\n ).parseDiagnostics ?? [];\n\n for (const diagnostic of parseDiagnostics) {\n const position = diagnostic.start ?? 0;\n const { line, character } =\n sourceFile.getLineAndCharacterOfPosition(position);\n\n diagnostics.push({\n code: \"syntax-error\",\n file: fileName,\n line: line + 1,\n column: character + 1,\n message: ts.flattenDiagnosticMessageText(diagnostic.messageText, \"\\n\"),\n });\n }\n\n const visit = (node: ts.Node): void => {\n if (\n ts.isCallExpression(node) &&\n callees.has(getCalleeName(node.expression) ?? \"\")\n ) {\n const keyExpression = node.arguments[0];\n const key = getStaticKey(keyExpression);\n\n if (key !== undefined && keyExpression) {\n keys.add(key);\n calls.push({ key, keyExpression });\n } else if (keyExpression) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(\n keyExpression.getStart(sourceFile),\n );\n diagnostics.push({\n code: \"dynamic-key\",\n file: fileName,\n line: line + 1,\n column: character + 1,\n message:\n \"Translation keys must be string literals for reliable catalog scanning.\",\n });\n }\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n\n return {\n sourceFile,\n keys: Object.freeze([...keys].sort()),\n calls: Object.freeze(calls),\n diagnostics: Object.freeze(diagnostics),\n };\n};\n\nconst encodeVlq = (value: number): string => {\n const alphabet =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n let encoded = \"\";\n let vlq = value < 0 ? ((-value) << 1) | 1 : value << 1;\n\n do {\n let digit = vlq & 31;\n vlq >>>= 5;\n\n if (vlq > 0) {\n digit |= 32;\n }\n\n encoded += alphabet[digit];\n } while (vlq > 0);\n\n return encoded;\n};\n\nconst getLineStarts = (source: string): number[] => {\n const starts = [0];\n\n for (let index = 0; index < source.length; index += 1) {\n const character = source[index];\n\n if (character === \"\\r\") {\n if (source[index + 1] === \"\\n\") {\n index += 1;\n }\n\n starts.push(index + 1);\n } else if (\n character === \"\\n\" ||\n character === \"\\u2028\" ||\n character === \"\\u2029\"\n ) {\n starts.push(index + 1);\n }\n }\n\n return starts;\n};\n\nconst getLineAndColumn = (\n lineStarts: readonly number[],\n position: number,\n): { line: number; column: number } => {\n let low = 0;\n let high = lineStarts.length;\n\n while (low < high) {\n const middle = Math.floor((low + high) / 2);\n\n if ((lineStarts[middle] ?? 0) <= position) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n\n const line = Math.max(0, low - 1);\n return {\n line,\n column: position - (lineStarts[line] ?? 0),\n };\n};\n\nconst createSourceMap = (\n fileName: string,\n source: string,\n code: string,\n edits: readonly AppliedEdit[],\n): string => {\n const sourceLineStarts = getLineStarts(source);\n const outputLineStarts = getLineStarts(code);\n const segmentsByLine = new Map<\n number,\n Map<number, { source: number; originalLine: number; originalColumn: number }>\n >();\n\n const addAnchor = (generatedPosition: number, originalPosition: number): void => {\n const generated = getLineAndColumn(outputLineStarts, generatedPosition);\n const original = getLineAndColumn(sourceLineStarts, originalPosition);\n let segments = segmentsByLine.get(generated.line);\n\n if (!segments) {\n segments = new Map();\n segmentsByLine.set(generated.line, segments);\n }\n\n segments.set(generated.column, {\n source: 0,\n originalLine: original.line,\n originalColumn: original.column,\n });\n };\n\n for (let line = 0; line < outputLineStarts.length; line += 1) {\n addAnchor(\n outputLineStarts[line] ?? code.length,\n sourceLineStarts[line] ?? source.length,\n );\n }\n\n for (const edit of edits) {\n addAnchor(edit.outputStart, edit.start);\n addAnchor(edit.outputEnd, edit.end);\n }\n\n const mapOutputPosition = (position: number): number => {\n let offset = 0;\n\n for (const edit of edits) {\n if (position < edit.outputStart) {\n return position - offset;\n }\n\n if (position <= edit.outputEnd) {\n return position === edit.outputEnd ? edit.end : edit.start;\n }\n\n offset += edit.replacement.length - (edit.end - edit.start);\n }\n\n return position - offset;\n };\n const scanner = ts.createScanner(\n ts.ScriptTarget.Latest,\n false,\n fileName.endsWith(\".tsx\") || fileName.endsWith(\".jsx\")\n ? ts.LanguageVariant.JSX\n : ts.LanguageVariant.Standard,\n code,\n );\n let token = scanner.scan();\n\n while (token !== ts.SyntaxKind.EndOfFileToken) {\n addAnchor(scanner.getTokenPos(), mapOutputPosition(scanner.getTokenPos()));\n addAnchor(scanner.getTextPos(), mapOutputPosition(scanner.getTextPos()));\n token = scanner.scan();\n }\n\n let previousSource = 0;\n let previousOriginalLine = 0;\n let previousOriginalColumn = 0;\n const mappings = outputLineStarts.map((_, line) => {\n const segments = [...(segmentsByLine.get(line)?.entries() ?? [])].sort(\n ([left], [right]) => left - right,\n );\n let previousGeneratedColumn = 0;\n\n return segments\n .map(([generatedColumn, mapping]) => {\n const encoded = [\n encodeVlq(generatedColumn - previousGeneratedColumn),\n encodeVlq(mapping.source - previousSource),\n encodeVlq(mapping.originalLine - previousOriginalLine),\n encodeVlq(mapping.originalColumn - previousOriginalColumn),\n ].join(\"\");\n\n previousGeneratedColumn = generatedColumn;\n previousSource = mapping.source;\n previousOriginalLine = mapping.originalLine;\n previousOriginalColumn = mapping.originalColumn;\n return encoded;\n })\n .join(\",\");\n });\n\n return JSON.stringify({\n version: 3,\n file: fileName,\n sources: [fileName],\n sourcesContent: [source],\n names: [],\n mappings: mappings.join(\";\"),\n });\n};\n\nconst toStringLiteral = (value: string): string =>\n JSON.stringify(value).replace(/[\\u2028\\u2029]/g, (character) => {\n const code = character.charCodeAt(0).toString(16);\n return `\\\\u${code}`;\n });\n\nexport const extractTranslationKeys = (\n source: string,\n options: ExtractTranslationKeysOptions = {},\n): ExtractedTranslationKeys => {\n const result = analyzeSource(source, options);\n\n return {\n keys: result.keys,\n diagnostics: result.diagnostics,\n };\n};\n\nexport const transformTranslationKeys = (\n source: string,\n options: TransformTranslationKeysOptions,\n): TransformTranslationKeysResult => {\n const fileName = options.fileName ?? \"source.ts\";\n const analysis = analyzeSource(source, options);\n const diagnostics = [...analysis.diagnostics];\n const edits: TextEdit[] = [];\n\n if (!diagnostics.some((diagnostic) => diagnostic.code === \"syntax-error\")) {\n for (const { key, keyExpression } of analysis.calls) {\n if (!Object.hasOwn(options.replacements, key)) {\n continue;\n }\n\n const replacement: unknown = options.replacements[key];\n\n if (typeof replacement !== \"string\") {\n const { line, character } =\n analysis.sourceFile.getLineAndCharacterOfPosition(\n keyExpression.getStart(analysis.sourceFile),\n );\n diagnostics.push({\n code: \"invalid-replacement\",\n file: fileName,\n line: line + 1,\n column: character + 1,\n key,\n message: `Replacement for \"${key}\" must be a string.`,\n });\n continue;\n }\n\n if (replacement !== key) {\n edits.push({\n start: keyExpression.getStart(analysis.sourceFile),\n end: keyExpression.getEnd(),\n replacement: toStringLiteral(replacement),\n });\n }\n }\n }\n\n edits.sort((left, right) => left.start - right.start || left.end - right.end);\n\n for (let index = 1; index < edits.length; index += 1) {\n const previous = edits[index - 1];\n const current = edits[index];\n\n if (previous && current && current.start < previous.end) {\n const { line, character } =\n analysis.sourceFile.getLineAndCharacterOfPosition(current.start);\n diagnostics.push({\n code: \"overlapping-replacement\",\n file: fileName,\n line: line + 1,\n column: character + 1,\n message:\n \"Overlapping translation-key replacements were rejected; source was left unchanged.\",\n });\n return {\n code: source,\n map: options.sourceMap === false\n ? null\n : createSourceMap(fileName, source, source, []),\n diagnostics: Object.freeze(diagnostics),\n };\n }\n }\n\n let code = \"\";\n let sourceOffset = 0;\n const appliedEdits: AppliedEdit[] = [];\n\n for (const edit of edits) {\n code += source.slice(sourceOffset, edit.start);\n const outputStart = code.length;\n code += edit.replacement;\n const outputEnd = code.length;\n appliedEdits.push({ ...edit, outputStart, outputEnd });\n sourceOffset = edit.end;\n }\n\n code += source.slice(sourceOffset);\n\n return {\n code,\n map:\n options.sourceMap === false\n ? null\n : createSourceMap(fileName, source, code, appliedEdits),\n diagnostics: Object.freeze(diagnostics),\n };\n};\n"],"mappings":";;AA0DA,MAAM,iBAAiB,eAAkD;CACvE,IAAI,GAAG,aAAa,UAAU,GAC5B,OAAO,WAAW;CAGpB,IAAI,GAAG,2BAA2B,UAAU,GAC1C,OAAO,WAAW,KAAK;CAGzB,IACE,GAAG,0BAA0B,UAAU,KACvC,WAAW,sBACX,GAAG,oBAAoB,WAAW,kBAAkB,GAEpD,OAAO,WAAW,mBAAmB;AAIzC;AAEA,MAAM,gBAAgB,eAA8D;CAClF,IACE,eACC,GAAG,oBAAoB,UAAU,KAChC,GAAG,gCAAgC,UAAU,IAE/C,OAAO,WAAW;AAItB;AAEA,MAAM,iBAAiB,aACrB,SAAS,SAAS,MAAM,IACpB,GAAG,WAAW,MACd,SAAS,SAAS,MAAM,IACtB,GAAG,WAAW,MACd,GAAG,WAAW;AAEtB,MAAM,iBACJ,QACA,YACmB;CACnB,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,aAAa,GAAG,iBACpB,UACA,QACA,GAAG,aAAa,QAChB,MACA,cAAc,QAAQ,CACxB;CACA,MAAM,UAAU,IAAI,IAAI,QAAQ,WAAW,CAAC,KAAK,WAAW,CAAC;CAC7D,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,QAA2B,CAAC;CAClC,MA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object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_compiler_index = require("./index.cjs");
|
|
3
|
+
const require_compiler_typescript = require("./typescript.cjs");
|
|
4
|
+
const require_sources_index = require("../sources/index.cjs");
|
|
5
|
+
let node_fs_promises = require("node:fs/promises");
|
|
6
|
+
let node_path = require("node:path");
|
|
7
|
+
// src/compiler/vite.ts
|
|
8
|
+
const SOURCE_EXTENSION = /\.(?:tsx?|jsx?|mts|cts|mjs|cjs)$/;
|
|
9
|
+
const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
|
|
10
|
+
".git",
|
|
11
|
+
".next",
|
|
12
|
+
".turbo",
|
|
13
|
+
"build",
|
|
14
|
+
"coverage",
|
|
15
|
+
"dist",
|
|
16
|
+
"node_modules"
|
|
17
|
+
]);
|
|
18
|
+
const canonicalLocale = (locale) => {
|
|
19
|
+
try {
|
|
20
|
+
return Intl.getCanonicalLocales(locale)[0];
|
|
21
|
+
} catch {
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
const collectSourceFiles = async (directory) => {
|
|
26
|
+
const files = [];
|
|
27
|
+
const visit = async (currentDirectory) => {
|
|
28
|
+
const entries = await (0, node_fs_promises.readdir)(currentDirectory, { withFileTypes: true });
|
|
29
|
+
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
30
|
+
const path = (0, node_path.resolve)(currentDirectory, entry.name);
|
|
31
|
+
if (entry.isDirectory()) {
|
|
32
|
+
if (!IGNORED_DIRECTORIES.has(entry.name)) await visit(path);
|
|
33
|
+
} else if (entry.isFile() && SOURCE_EXTENSION.test(entry.name)) files.push(path);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
await visit(directory);
|
|
37
|
+
return files;
|
|
38
|
+
};
|
|
39
|
+
const validateI18nProject = async (options, root = process.cwd()) => {
|
|
40
|
+
if (options.sourceDirectories.length === 0) throw new Error("At least one source directory must be configured.");
|
|
41
|
+
const catalogPath = (0, node_path.resolve)(root, options.catalogDirectory);
|
|
42
|
+
const catalogFiles = (await (0, node_fs_promises.readdir)(catalogPath, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).sort((left, right) => left.name.localeCompare(right.name));
|
|
43
|
+
if (catalogFiles.length === 0) throw new Error(`No JSON catalogs were found in "${catalogPath}".`);
|
|
44
|
+
const catalogs = {};
|
|
45
|
+
const watchedFiles = [catalogPath];
|
|
46
|
+
for (const file of catalogFiles) {
|
|
47
|
+
const path = (0, node_path.resolve)(catalogPath, file.name);
|
|
48
|
+
const locale = (0, node_path.basename)(file.name, ".json");
|
|
49
|
+
catalogs[locale] = require_sources_index.parseJsonCatalog(await (0, node_fs_promises.readFile)(path, "utf8"), locale);
|
|
50
|
+
watchedFiles.push(path);
|
|
51
|
+
}
|
|
52
|
+
const diagnostics = require_compiler_index.validateCatalogs({
|
|
53
|
+
catalogs,
|
|
54
|
+
defaultLocale: options.defaultLocale
|
|
55
|
+
}).map((issue) => `[${issue.code}] ${issue.locale}${issue.key ? ` ${issue.key}` : ""}: ${issue.message}`);
|
|
56
|
+
const sourceFiles = (await Promise.all(options.sourceDirectories.map((directory) => collectSourceFiles((0, node_path.resolve)(root, directory))))).flat().sort();
|
|
57
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
58
|
+
for (const file of sourceFiles) {
|
|
59
|
+
const result = require_compiler_typescript.extractTranslationKeys(await (0, node_fs_promises.readFile)(file, "utf8"), {
|
|
60
|
+
fileName: file,
|
|
61
|
+
callees: options.callees
|
|
62
|
+
});
|
|
63
|
+
result.keys.forEach((key) => usedKeys.add(key));
|
|
64
|
+
diagnostics.push(...result.diagnostics.map((diagnostic) => `[${diagnostic.code}] ${diagnostic.file}:${diagnostic.line}:${diagnostic.column}: ${diagnostic.message}`));
|
|
65
|
+
}
|
|
66
|
+
watchedFiles.push(...options.sourceDirectories.map((directory) => (0, node_path.resolve)(root, directory)));
|
|
67
|
+
watchedFiles.push(...sourceFiles);
|
|
68
|
+
const resolvedDefaultLocale = canonicalLocale(options.defaultLocale);
|
|
69
|
+
const defaultCatalog = resolvedDefaultLocale ? Object.entries(catalogs).find(([locale]) => canonicalLocale(locale) === resolvedDefaultLocale)?.[1] : void 0;
|
|
70
|
+
if (defaultCatalog) diagnostics.push(...require_compiler_index.findMissingTranslationKeys(defaultCatalog, usedKeys).map((key) => `[missing-key] ${key}: referenced in source but absent from the default catalog.`), ...require_compiler_index.findUnusedTranslationKeys(defaultCatalog, usedKeys).map((key) => `[unused-key] ${key}: present in the default catalog but not referenced in source.`));
|
|
71
|
+
return {
|
|
72
|
+
diagnostics: Object.freeze(diagnostics),
|
|
73
|
+
watchedFiles: Object.freeze([...new Set(watchedFiles)])
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
const puzzleI18n = (options) => {
|
|
77
|
+
let root = process.cwd();
|
|
78
|
+
return {
|
|
79
|
+
name: "@puzzle-ui/i18n",
|
|
80
|
+
enforce: "pre",
|
|
81
|
+
configResolved(config) {
|
|
82
|
+
root = config.root;
|
|
83
|
+
},
|
|
84
|
+
async buildStart() {
|
|
85
|
+
const result = await validateI18nProject(options, root);
|
|
86
|
+
result.watchedFiles.forEach((file) => this.addWatchFile(file));
|
|
87
|
+
if (result.diagnostics.length > 0) this.error(`Puzzle i18n validation failed:\n${result.diagnostics.join("\n")}`);
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
exports.puzzleI18n = puzzleI18n;
|
|
92
|
+
exports.validateI18nProject = validateI18nProject;
|
|
93
|
+
|
|
94
|
+
//# sourceMappingURL=vite.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.cjs","names":["readdir","resolve","basename","parseJsonCatalog","readFile","validateCatalogs","extractTranslationKeys","findMissingTranslationKeys","findUnusedTranslationKeys"],"sources":["../../src/compiler/vite.ts"],"sourcesContent":["import { readdir, readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\n\nimport type { Plugin } from \"vite\";\nimport {\n findMissingTranslationKeys,\n findUnusedTranslationKeys,\n validateCatalogs,\n} from \".\";\nimport { extractTranslationKeys } from \"./typescript\";\nimport { parseJsonCatalog } from \"../sources\";\n\nexport interface I18nVitePluginOptions {\n catalogDirectory: string;\n sourceDirectories: readonly string[];\n defaultLocale: string;\n callees?: readonly string[];\n}\n\nexport interface I18nViteValidationResult {\n diagnostics: readonly string[];\n watchedFiles: readonly string[];\n}\n\nconst SOURCE_EXTENSION = /\\.(?:tsx?|jsx?|mts|cts|mjs|cjs)$/;\nconst IGNORED_DIRECTORIES = new Set([\n \".git\",\n \".next\",\n \".turbo\",\n \"build\",\n \"coverage\",\n \"dist\",\n \"node_modules\",\n]);\n\nconst canonicalLocale = (locale: string): string | undefined => {\n try {\n return Intl.getCanonicalLocales(locale)[0];\n } catch {\n return undefined;\n }\n};\n\nconst collectSourceFiles = async (directory: string): Promise<string[]> => {\n const files: string[] = [];\n\n const visit = async (currentDirectory: string): Promise<void> => {\n const entries = await readdir(currentDirectory, { withFileTypes: true });\n\n for (const entry of entries.sort((left, right) =>\n left.name.localeCompare(right.name),\n )) {\n const path = resolve(currentDirectory, entry.name);\n\n if (entry.isDirectory()) {\n if (!IGNORED_DIRECTORIES.has(entry.name)) {\n await visit(path);\n }\n } else if (entry.isFile() && SOURCE_EXTENSION.test(entry.name)) {\n files.push(path);\n }\n }\n };\n\n await visit(directory);\n return files;\n};\n\nexport const validateI18nProject = async (\n options: I18nVitePluginOptions,\n root = process.cwd(),\n): Promise<I18nViteValidationResult> => {\n if (options.sourceDirectories.length === 0) {\n throw new Error(\"At least one source directory must be configured.\");\n }\n\n const catalogPath = resolve(root, options.catalogDirectory);\n const catalogFiles = (await readdir(catalogPath, { withFileTypes: true }))\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .sort((left, right) => left.name.localeCompare(right.name));\n\n if (catalogFiles.length === 0) {\n throw new Error(`No JSON catalogs were found in \"${catalogPath}\".`);\n }\n\n const catalogs: Record<string, ReturnType<typeof parseJsonCatalog>> = {};\n const watchedFiles = [catalogPath];\n\n for (const file of catalogFiles) {\n const path = resolve(catalogPath, file.name);\n const locale = basename(file.name, \".json\");\n catalogs[locale] = parseJsonCatalog(await readFile(path, \"utf8\"), locale);\n watchedFiles.push(path);\n }\n\n const diagnostics = validateCatalogs({\n catalogs,\n defaultLocale: options.defaultLocale,\n }).map(\n (issue) =>\n `[${issue.code}] ${issue.locale}${issue.key ? ` ${issue.key}` : \"\"}: ${issue.message}`,\n );\n const sourceFiles = (\n await Promise.all(\n options.sourceDirectories.map((directory) =>\n collectSourceFiles(resolve(root, directory)),\n ),\n )\n )\n .flat()\n .sort();\n const usedKeys = new Set<string>();\n\n for (const file of sourceFiles) {\n const result = extractTranslationKeys(await readFile(file, \"utf8\"), {\n fileName: file,\n callees: options.callees,\n });\n\n result.keys.forEach((key) => usedKeys.add(key));\n diagnostics.push(\n ...result.diagnostics.map(\n (diagnostic) =>\n `[${diagnostic.code}] ${diagnostic.file}:${diagnostic.line}:${diagnostic.column}: ${diagnostic.message}`,\n ),\n );\n }\n\n watchedFiles.push(...options.sourceDirectories.map((directory) => resolve(root, directory)));\n watchedFiles.push(...sourceFiles);\n\n const resolvedDefaultLocale = canonicalLocale(options.defaultLocale);\n const defaultCatalog = resolvedDefaultLocale\n ? Object.entries(catalogs).find(\n ([locale]) => canonicalLocale(locale) === resolvedDefaultLocale,\n )?.[1]\n : undefined;\n\n if (defaultCatalog) {\n diagnostics.push(\n ...findMissingTranslationKeys(defaultCatalog, usedKeys).map(\n (key) =>\n `[missing-key] ${key}: referenced in source but absent from the default catalog.`,\n ),\n ...findUnusedTranslationKeys(defaultCatalog, usedKeys).map(\n (key) =>\n `[unused-key] ${key}: present in the default catalog but not referenced in source.`,\n ),\n );\n }\n\n return {\n diagnostics: Object.freeze(diagnostics),\n watchedFiles: Object.freeze([...new Set(watchedFiles)]),\n };\n};\n\nexport const puzzleI18n = (options: I18nVitePluginOptions): Plugin => {\n let root = process.cwd();\n\n return {\n name: \"@puzzle-ui/i18n\",\n enforce: \"pre\",\n configResolved(config) {\n root = config.root;\n },\n async buildStart() {\n const result = await validateI18nProject(options, root);\n\n result.watchedFiles.forEach((file) => this.addWatchFile(file));\n\n if (result.diagnostics.length > 0) {\n this.error(\n `Puzzle i18n validation failed:\\n${result.diagnostics.join(\"\\n\")}`,\n );\n }\n },\n };\n};\n"],"mappings":";;;;;;;AAwBA,MAAM,mBAAmB;AACzB,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,WAAuC;CAC9D,IAAI;EACF,OAAO,KAAK,oBAAoB,MAAM,CAAC,CAAC;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,MAAM,qBAAqB,OAAO,cAAyC;CACzE,MAAM,QAAkB,CAAC;CAEzB,MAAM,QAAQ,OAAO,qBAA4C;EAC/D,MAAM,UAAU,OAAA,GAAMA,iBAAAA,QAAAA,CAAQ,kBAAkB,EAAE,eAAe,KAAK,CAAC;EAEvE,KAAK,MAAM,SAAS,QAAQ,MAAM,MAAM,UACtC,KAAK,KAAK,cAAc,MAAM,IAAI,CACpC,GAAG;GACD,MAAM,QAAA,GAAOC,UAAAA,QAAAA,CAAQ,kBAAkB,MAAM,IAAI;GAEjD,IAAI,MAAM,YAAY,GAChB;QAAA,CAAC,oBAAoB,IAAI,MAAM,IAAI,GACrC,MAAM,MAAM,IAAI;GAAA,OAEb,IAAI,MAAM,OAAO,KAAK,iBAAiB,KAAK,MAAM,IAAI,GAC3D,MAAM,KAAK,IAAI;EAEnB;CACF;CAEA,MAAM,MAAM,SAAS;CACrB,OAAO;AACT;AAEA,MAAa,sBAAsB,OACjC,SACA,OAAO,QAAQ,IAAI,MACmB;CACtC,IAAI,QAAQ,kBAAkB,WAAW,GACvC,MAAM,IAAI,MAAM,mDAAmD;CAGrE,MAAM,eAAA,GAAcA,UAAAA,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plugin } from "vite";
|
|
2
|
+
export interface I18nVitePluginOptions {
|
|
3
|
+
catalogDirectory: string;
|
|
4
|
+
sourceDirectories: readonly string[];
|
|
5
|
+
defaultLocale: string;
|
|
6
|
+
callees?: readonly string[];
|
|
7
|
+
}
|
|
8
|
+
export interface I18nViteValidationResult {
|
|
9
|
+
diagnostics: readonly string[];
|
|
10
|
+
watchedFiles: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
export declare const validateI18nProject: (options: I18nVitePluginOptions, root?: string) => Promise<I18nViteValidationResult>;
|
|
13
|
+
export declare const puzzleI18n: (options: I18nVitePluginOptions) => Plugin;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Plugin } from "vite";
|
|
2
|
+
export interface I18nVitePluginOptions {
|
|
3
|
+
catalogDirectory: string;
|
|
4
|
+
sourceDirectories: readonly string[];
|
|
5
|
+
defaultLocale: string;
|
|
6
|
+
callees?: readonly string[];
|
|
7
|
+
}
|
|
8
|
+
export interface I18nViteValidationResult {
|
|
9
|
+
diagnostics: readonly string[];
|
|
10
|
+
watchedFiles: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
export declare const validateI18nProject: (options: I18nVitePluginOptions, root?: string) => Promise<I18nViteValidationResult>;
|
|
13
|
+
export declare const puzzleI18n: (options: I18nVitePluginOptions) => Plugin;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { findMissingTranslationKeys, findUnusedTranslationKeys, validateCatalogs } from "./index.js";
|
|
2
|
+
import { extractTranslationKeys } from "./typescript.js";
|
|
3
|
+
import { parseJsonCatalog } from "../sources/index.js";
|
|
4
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
5
|
+
import { basename, resolve } from "node:path";
|
|
6
|
+
// src/compiler/vite.ts
|
|
7
|
+
const SOURCE_EXTENSION = /\.(?:tsx?|jsx?|mts|cts|mjs|cjs)$/;
|
|
8
|
+
const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
|
|
9
|
+
".git",
|
|
10
|
+
".next",
|
|
11
|
+
".turbo",
|
|
12
|
+
"build",
|
|
13
|
+
"coverage",
|
|
14
|
+
"dist",
|
|
15
|
+
"node_modules"
|
|
16
|
+
]);
|
|
17
|
+
const canonicalLocale = (locale) => {
|
|
18
|
+
try {
|
|
19
|
+
return Intl.getCanonicalLocales(locale)[0];
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
const collectSourceFiles = async (directory) => {
|
|
25
|
+
const files = [];
|
|
26
|
+
const visit = async (currentDirectory) => {
|
|
27
|
+
const entries = await readdir(currentDirectory, { withFileTypes: true });
|
|
28
|
+
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
29
|
+
const path = resolve(currentDirectory, entry.name);
|
|
30
|
+
if (entry.isDirectory()) {
|
|
31
|
+
if (!IGNORED_DIRECTORIES.has(entry.name)) await visit(path);
|
|
32
|
+
} else if (entry.isFile() && SOURCE_EXTENSION.test(entry.name)) files.push(path);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
await visit(directory);
|
|
36
|
+
return files;
|
|
37
|
+
};
|
|
38
|
+
const validateI18nProject = async (options, root = process.cwd()) => {
|
|
39
|
+
if (options.sourceDirectories.length === 0) throw new Error("At least one source directory must be configured.");
|
|
40
|
+
const catalogPath = resolve(root, options.catalogDirectory);
|
|
41
|
+
const catalogFiles = (await readdir(catalogPath, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).sort((left, right) => left.name.localeCompare(right.name));
|
|
42
|
+
if (catalogFiles.length === 0) throw new Error(`No JSON catalogs were found in "${catalogPath}".`);
|
|
43
|
+
const catalogs = {};
|
|
44
|
+
const watchedFiles = [catalogPath];
|
|
45
|
+
for (const file of catalogFiles) {
|
|
46
|
+
const path = resolve(catalogPath, file.name);
|
|
47
|
+
const locale = basename(file.name, ".json");
|
|
48
|
+
catalogs[locale] = parseJsonCatalog(await readFile(path, "utf8"), locale);
|
|
49
|
+
watchedFiles.push(path);
|
|
50
|
+
}
|
|
51
|
+
const diagnostics = validateCatalogs({
|
|
52
|
+
catalogs,
|
|
53
|
+
defaultLocale: options.defaultLocale
|
|
54
|
+
}).map((issue) => `[${issue.code}] ${issue.locale}${issue.key ? ` ${issue.key}` : ""}: ${issue.message}`);
|
|
55
|
+
const sourceFiles = (await Promise.all(options.sourceDirectories.map((directory) => collectSourceFiles(resolve(root, directory))))).flat().sort();
|
|
56
|
+
const usedKeys = /* @__PURE__ */ new Set();
|
|
57
|
+
for (const file of sourceFiles) {
|
|
58
|
+
const result = extractTranslationKeys(await readFile(file, "utf8"), {
|
|
59
|
+
fileName: file,
|
|
60
|
+
callees: options.callees
|
|
61
|
+
});
|
|
62
|
+
result.keys.forEach((key) => usedKeys.add(key));
|
|
63
|
+
diagnostics.push(...result.diagnostics.map((diagnostic) => `[${diagnostic.code}] ${diagnostic.file}:${diagnostic.line}:${diagnostic.column}: ${diagnostic.message}`));
|
|
64
|
+
}
|
|
65
|
+
watchedFiles.push(...options.sourceDirectories.map((directory) => resolve(root, directory)));
|
|
66
|
+
watchedFiles.push(...sourceFiles);
|
|
67
|
+
const resolvedDefaultLocale = canonicalLocale(options.defaultLocale);
|
|
68
|
+
const defaultCatalog = resolvedDefaultLocale ? Object.entries(catalogs).find(([locale]) => canonicalLocale(locale) === resolvedDefaultLocale)?.[1] : void 0;
|
|
69
|
+
if (defaultCatalog) diagnostics.push(...findMissingTranslationKeys(defaultCatalog, usedKeys).map((key) => `[missing-key] ${key}: referenced in source but absent from the default catalog.`), ...findUnusedTranslationKeys(defaultCatalog, usedKeys).map((key) => `[unused-key] ${key}: present in the default catalog but not referenced in source.`));
|
|
70
|
+
return {
|
|
71
|
+
diagnostics: Object.freeze(diagnostics),
|
|
72
|
+
watchedFiles: Object.freeze([...new Set(watchedFiles)])
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
const puzzleI18n = (options) => {
|
|
76
|
+
let root = process.cwd();
|
|
77
|
+
return {
|
|
78
|
+
name: "@puzzle-ui/i18n",
|
|
79
|
+
enforce: "pre",
|
|
80
|
+
configResolved(config) {
|
|
81
|
+
root = config.root;
|
|
82
|
+
},
|
|
83
|
+
async buildStart() {
|
|
84
|
+
const result = await validateI18nProject(options, root);
|
|
85
|
+
result.watchedFiles.forEach((file) => this.addWatchFile(file));
|
|
86
|
+
if (result.diagnostics.length > 0) this.error(`Puzzle i18n validation failed:\n${result.diagnostics.join("\n")}`);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
export { puzzleI18n, validateI18nProject };
|
|
91
|
+
|
|
92
|
+
//# sourceMappingURL=vite.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../../src/compiler/vite.ts"],"sourcesContent":["import { readdir, readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\n\nimport type { Plugin } from \"vite\";\nimport {\n findMissingTranslationKeys,\n findUnusedTranslationKeys,\n validateCatalogs,\n} from \".\";\nimport { extractTranslationKeys } from \"./typescript\";\nimport { parseJsonCatalog } from \"../sources\";\n\nexport interface I18nVitePluginOptions {\n catalogDirectory: string;\n sourceDirectories: readonly string[];\n defaultLocale: string;\n callees?: readonly string[];\n}\n\nexport interface I18nViteValidationResult {\n diagnostics: readonly string[];\n watchedFiles: readonly string[];\n}\n\nconst SOURCE_EXTENSION = /\\.(?:tsx?|jsx?|mts|cts|mjs|cjs)$/;\nconst IGNORED_DIRECTORIES = new Set([\n \".git\",\n \".next\",\n \".turbo\",\n \"build\",\n \"coverage\",\n \"dist\",\n \"node_modules\",\n]);\n\nconst canonicalLocale = (locale: string): string | undefined => {\n try {\n return Intl.getCanonicalLocales(locale)[0];\n } catch {\n return undefined;\n }\n};\n\nconst collectSourceFiles = async (directory: string): Promise<string[]> => {\n const files: string[] = [];\n\n const visit = async (currentDirectory: string): Promise<void> => {\n const entries = await readdir(currentDirectory, { withFileTypes: true });\n\n for (const entry of entries.sort((left, right) =>\n left.name.localeCompare(right.name),\n )) {\n const path = resolve(currentDirectory, entry.name);\n\n if (entry.isDirectory()) {\n if (!IGNORED_DIRECTORIES.has(entry.name)) {\n await visit(path);\n }\n } else if (entry.isFile() && SOURCE_EXTENSION.test(entry.name)) {\n files.push(path);\n }\n }\n };\n\n await visit(directory);\n return files;\n};\n\nexport const validateI18nProject = async (\n options: I18nVitePluginOptions,\n root = process.cwd(),\n): Promise<I18nViteValidationResult> => {\n if (options.sourceDirectories.length === 0) {\n throw new Error(\"At least one source directory must be configured.\");\n }\n\n const catalogPath = resolve(root, options.catalogDirectory);\n const catalogFiles = (await readdir(catalogPath, { withFileTypes: true }))\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .sort((left, right) => left.name.localeCompare(right.name));\n\n if (catalogFiles.length === 0) {\n throw new Error(`No JSON catalogs were found in \"${catalogPath}\".`);\n }\n\n const catalogs: Record<string, ReturnType<typeof parseJsonCatalog>> = {};\n const watchedFiles = [catalogPath];\n\n for (const file of catalogFiles) {\n const path = resolve(catalogPath, file.name);\n const locale = basename(file.name, \".json\");\n catalogs[locale] = parseJsonCatalog(await readFile(path, \"utf8\"), locale);\n watchedFiles.push(path);\n }\n\n const diagnostics = validateCatalogs({\n catalogs,\n defaultLocale: options.defaultLocale,\n }).map(\n (issue) =>\n `[${issue.code}] ${issue.locale}${issue.key ? ` ${issue.key}` : \"\"}: ${issue.message}`,\n );\n const sourceFiles = (\n await Promise.all(\n options.sourceDirectories.map((directory) =>\n collectSourceFiles(resolve(root, directory)),\n ),\n )\n )\n .flat()\n .sort();\n const usedKeys = new Set<string>();\n\n for (const file of sourceFiles) {\n const result = extractTranslationKeys(await readFile(file, \"utf8\"), {\n fileName: file,\n callees: options.callees,\n });\n\n result.keys.forEach((key) => usedKeys.add(key));\n diagnostics.push(\n ...result.diagnostics.map(\n (diagnostic) =>\n `[${diagnostic.code}] ${diagnostic.file}:${diagnostic.line}:${diagnostic.column}: ${diagnostic.message}`,\n ),\n );\n }\n\n watchedFiles.push(...options.sourceDirectories.map((directory) => resolve(root, directory)));\n watchedFiles.push(...sourceFiles);\n\n const resolvedDefaultLocale = canonicalLocale(options.defaultLocale);\n const defaultCatalog = resolvedDefaultLocale\n ? Object.entries(catalogs).find(\n ([locale]) => canonicalLocale(locale) === resolvedDefaultLocale,\n )?.[1]\n : undefined;\n\n if (defaultCatalog) {\n diagnostics.push(\n ...findMissingTranslationKeys(defaultCatalog, usedKeys).map(\n (key) =>\n `[missing-key] ${key}: referenced in source but absent from the default catalog.`,\n ),\n ...findUnusedTranslationKeys(defaultCatalog, usedKeys).map(\n (key) =>\n `[unused-key] ${key}: present in the default catalog but not referenced in source.`,\n ),\n );\n }\n\n return {\n diagnostics: Object.freeze(diagnostics),\n watchedFiles: Object.freeze([...new Set(watchedFiles)]),\n };\n};\n\nexport const puzzleI18n = (options: I18nVitePluginOptions): Plugin => {\n let root = process.cwd();\n\n return {\n name: \"@puzzle-ui/i18n\",\n enforce: \"pre\",\n configResolved(config) {\n root = config.root;\n },\n async buildStart() {\n const result = await validateI18nProject(options, root);\n\n result.watchedFiles.forEach((file) => this.addWatchFile(file));\n\n if (result.diagnostics.length > 0) {\n this.error(\n `Puzzle i18n validation failed:\\n${result.diagnostics.join(\"\\n\")}`,\n );\n }\n },\n };\n};\n"],"mappings":";;;;;;AAwBA,MAAM,mBAAmB;AACzB,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,WAAuC;CAC9D,IAAI;EACF,OAAO,KAAK,oBAAoB,MAAM,CAAC,CAAC;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,MAAM,qBAAqB,OAAO,cAAyC;CACzE,MAAM,QAAkB,CAAC;CAEzB,MAAM,QAAQ,OAAO,qBAA4C;EAC/D,MAAM,UAAU,MAAM,QAAQ,kBAAkB,EAAE,eAAe,KAAK,CAAC;EAEvE,KAAK,MAA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