@zachhandley/ez-i18n 0.1.2 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,378 @@
1
+ import { glob } from 'tinyglobby';
2
+ import * as path from 'node:path';
3
+ import * as fs from 'node:fs';
4
+ import type { LocaleTranslationPath, TranslationsConfig, TranslationCache } from '../types';
5
+
6
+ const CACHE_FILE = '.ez-i18n.json';
7
+ const CACHE_VERSION = 1;
8
+ const DEFAULT_I18N_DIR = './public/i18n';
9
+
10
+ export type PathType = 'file' | 'folder' | 'glob' | 'array';
11
+
12
+ /**
13
+ * Detect the type of translation path
14
+ */
15
+ export function detectPathType(input: string | string[]): PathType {
16
+ if (Array.isArray(input)) return 'array';
17
+ if (input.includes('*')) return 'glob';
18
+ if (input.endsWith('/') || input.endsWith(path.sep)) return 'folder';
19
+ return 'file';
20
+ }
21
+
22
+ /**
23
+ * Check if a path is a directory (handles missing trailing slash)
24
+ */
25
+ function isDirectory(filePath: string): boolean {
26
+ try {
27
+ return fs.statSync(filePath).isDirectory();
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Resolve a single translation path to an array of absolute file paths.
35
+ * Results are sorted alphabetically for predictable merge order.
36
+ */
37
+ export async function resolveTranslationPaths(
38
+ input: LocaleTranslationPath,
39
+ projectRoot: string
40
+ ): Promise<string[]> {
41
+ const type = detectPathType(input);
42
+ let files: string[] = [];
43
+
44
+ switch (type) {
45
+ case 'array':
46
+ // Each entry could itself be a glob, folder, or file
47
+ for (const entry of input as string[]) {
48
+ const resolved = await resolveTranslationPaths(entry, projectRoot);
49
+ files.push(...resolved);
50
+ }
51
+ break;
52
+
53
+ case 'glob':
54
+ files = await glob(input as string, {
55
+ cwd: projectRoot,
56
+ absolute: true,
57
+ });
58
+ break;
59
+
60
+ case 'folder': {
61
+ const folderPath = path.resolve(projectRoot, (input as string).replace(/\/$/, ''));
62
+ files = await glob('**/*.json', {
63
+ cwd: folderPath,
64
+ absolute: true,
65
+ });
66
+ break;
67
+ }
68
+
69
+ case 'file':
70
+ default: {
71
+ const filePath = path.resolve(projectRoot, input as string);
72
+ // Check if it's actually a directory (user omitted trailing slash)
73
+ if (isDirectory(filePath)) {
74
+ files = await glob('**/*.json', {
75
+ cwd: filePath,
76
+ absolute: true,
77
+ });
78
+ } else {
79
+ files = [filePath];
80
+ }
81
+ break;
82
+ }
83
+ }
84
+
85
+ // Sort alphabetically for predictable merge order
86
+ return [...new Set(files)].sort((a, b) => a.localeCompare(b));
87
+ }
88
+
89
+ /**
90
+ * Auto-discover translations from a base directory.
91
+ * Scans for locale folders (e.g., en/, es/, fr/) and their JSON files.
92
+ * Returns both discovered locales and their file mappings.
93
+ */
94
+ export async function autoDiscoverTranslations(
95
+ baseDir: string,
96
+ projectRoot: string,
97
+ configuredLocales?: string[]
98
+ ): Promise<{ locales: string[]; translations: Record<string, string[]> }> {
99
+ const absoluteBaseDir = path.resolve(projectRoot, baseDir.replace(/\/$/, ''));
100
+
101
+ if (!isDirectory(absoluteBaseDir)) {
102
+ console.warn(`[ez-i18n] Translation directory not found: ${absoluteBaseDir}`);
103
+ return { locales: configuredLocales || [], translations: {} };
104
+ }
105
+
106
+ const translations: Record<string, string[]> = {};
107
+ const discoveredLocales: string[] = [];
108
+
109
+ // Read directory entries
110
+ const entries = fs.readdirSync(absoluteBaseDir, { withFileTypes: true });
111
+
112
+ for (const entry of entries) {
113
+ if (entry.isDirectory()) {
114
+ // This is a locale folder (e.g., en/, es/)
115
+ const locale = entry.name;
116
+
117
+ // If locales were configured, only include matching ones
118
+ if (configuredLocales && configuredLocales.length > 0) {
119
+ if (!configuredLocales.includes(locale)) continue;
120
+ }
121
+
122
+ const localePath = path.join(absoluteBaseDir, locale);
123
+ const files = await glob('**/*.json', {
124
+ cwd: localePath,
125
+ absolute: true,
126
+ });
127
+
128
+ if (files.length > 0) {
129
+ discoveredLocales.push(locale);
130
+ translations[locale] = files.sort((a, b) => a.localeCompare(b));
131
+ }
132
+ } else if (entry.isFile() && entry.name.endsWith('.json')) {
133
+ // Root-level JSON files (e.g., en.json, es.json)
134
+ // Extract locale from filename
135
+ const locale = path.basename(entry.name, '.json');
136
+
137
+ // If locales were configured, only include matching ones
138
+ if (configuredLocales && configuredLocales.length > 0) {
139
+ if (!configuredLocales.includes(locale)) continue;
140
+ }
141
+
142
+ const filePath = path.join(absoluteBaseDir, entry.name);
143
+
144
+ if (!translations[locale]) {
145
+ discoveredLocales.push(locale);
146
+ translations[locale] = [];
147
+ }
148
+ translations[locale].push(filePath);
149
+ }
150
+ }
151
+
152
+ // Sort locales for consistency
153
+ const sortedLocales = [...new Set(discoveredLocales)].sort();
154
+
155
+ return { locales: sortedLocales, translations };
156
+ }
157
+
158
+ /**
159
+ * Resolve the full translations config to normalized form.
160
+ * Handles string (base dir), object (per-locale), or undefined (auto-discover).
161
+ */
162
+ export async function resolveTranslationsConfig(
163
+ config: TranslationsConfig | undefined,
164
+ projectRoot: string,
165
+ configuredLocales?: string[]
166
+ ): Promise<{ locales: string[]; translations: Record<string, string[]> }> {
167
+ // No config - auto-discover from default location
168
+ if (!config) {
169
+ return autoDiscoverTranslations(DEFAULT_I18N_DIR, projectRoot, configuredLocales);
170
+ }
171
+
172
+ // String - treat as base directory for auto-discovery
173
+ if (typeof config === 'string') {
174
+ return autoDiscoverTranslations(config, projectRoot, configuredLocales);
175
+ }
176
+
177
+ // Object - per-locale mapping
178
+ const translations: Record<string, string[]> = {};
179
+ const locales = Object.keys(config);
180
+
181
+ for (const [locale, localePath] of Object.entries(config)) {
182
+ translations[locale] = await resolveTranslationPaths(localePath, projectRoot);
183
+ }
184
+
185
+ return { locales, translations };
186
+ }
187
+
188
+ /**
189
+ * Deep merge translation objects.
190
+ * - Objects are recursively merged
191
+ * - Arrays are REPLACED (not concatenated)
192
+ * - Primitives are overwritten by later values
193
+ * - Prototype pollution safe
194
+ */
195
+ export function deepMerge<T extends Record<string, unknown>>(
196
+ target: T,
197
+ ...sources: T[]
198
+ ): T {
199
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
200
+ const result = { ...target };
201
+
202
+ for (const source of sources) {
203
+ if (!source || typeof source !== 'object') continue;
204
+
205
+ for (const key of Object.keys(source)) {
206
+ if (FORBIDDEN_KEYS.has(key)) continue;
207
+
208
+ const targetVal = result[key as keyof T];
209
+ const sourceVal = source[key as keyof T];
210
+
211
+ if (
212
+ sourceVal !== null &&
213
+ typeof sourceVal === 'object' &&
214
+ !Array.isArray(sourceVal) &&
215
+ targetVal !== null &&
216
+ typeof targetVal === 'object' &&
217
+ !Array.isArray(targetVal)
218
+ ) {
219
+ // Both are plain objects - recurse
220
+ (result as Record<string, unknown>)[key] = deepMerge(
221
+ targetVal as Record<string, unknown>,
222
+ sourceVal as Record<string, unknown>
223
+ );
224
+ } else {
225
+ // Arrays replace, primitives overwrite
226
+ (result as Record<string, unknown>)[key] = sourceVal;
227
+ }
228
+ }
229
+ }
230
+
231
+ return result;
232
+ }
233
+
234
+ /**
235
+ * Load cached translation discovery results
236
+ */
237
+ export function loadCache(projectRoot: string): TranslationCache | null {
238
+ const cachePath = path.join(projectRoot, CACHE_FILE);
239
+
240
+ try {
241
+ if (!fs.existsSync(cachePath)) return null;
242
+
243
+ const content = fs.readFileSync(cachePath, 'utf-8');
244
+ const cache = JSON.parse(content) as TranslationCache;
245
+
246
+ // Validate cache version
247
+ if (cache.version !== CACHE_VERSION) return null;
248
+
249
+ return cache;
250
+ } catch {
251
+ return null;
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Save translation discovery results to cache
257
+ */
258
+ export function saveCache(
259
+ projectRoot: string,
260
+ discovered: Record<string, string[]>
261
+ ): void {
262
+ const cachePath = path.join(projectRoot, CACHE_FILE);
263
+
264
+ const cache: TranslationCache = {
265
+ version: CACHE_VERSION,
266
+ discovered,
267
+ lastScan: new Date().toISOString(),
268
+ };
269
+
270
+ try {
271
+ fs.writeFileSync(cachePath, JSON.stringify(cache, null, 2));
272
+ } catch (error) {
273
+ console.warn('[ez-i18n] Failed to write cache file:', error);
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Check if cache is still valid (files haven't changed)
279
+ */
280
+ export function isCacheValid(
281
+ cache: TranslationCache,
282
+ projectRoot: string
283
+ ): boolean {
284
+ // Check if all cached files still exist
285
+ for (const files of Object.values(cache.discovered)) {
286
+ for (const file of files) {
287
+ if (!fs.existsSync(file)) return false;
288
+ }
289
+ }
290
+
291
+ return true;
292
+ }
293
+
294
+ /**
295
+ * Convert an absolute path to a relative import path for Vite
296
+ */
297
+ export function toRelativeImport(absolutePath: string, projectRoot: string): string {
298
+ const relativePath = path.relative(projectRoot, absolutePath);
299
+ // Ensure it starts with ./ and uses forward slashes
300
+ const normalized = relativePath.replace(/\\/g, '/');
301
+ return normalized.startsWith('.') ? normalized : './' + normalized;
302
+ }
303
+
304
+ /**
305
+ * Generate a glob pattern for import.meta.glob from a base directory
306
+ */
307
+ export function toGlobPattern(baseDir: string, projectRoot: string): string {
308
+ const relativePath = path.relative(projectRoot, baseDir).replace(/\\/g, '/');
309
+ const normalized = relativePath.startsWith('.') ? relativePath : './' + relativePath;
310
+ return `${normalized}/**/*.json`;
311
+ }
312
+
313
+ /**
314
+ * Get namespace from file path relative to locale base directory.
315
+ *
316
+ * Examples:
317
+ * - filePath: /project/public/i18n/en/auth/login.json, localeDir: /project/public/i18n/en
318
+ * → namespace: 'auth.login'
319
+ * - filePath: /project/public/i18n/en/common.json, localeDir: /project/public/i18n/en
320
+ * → namespace: 'common'
321
+ * - filePath: /project/public/i18n/en/settings/index.json, localeDir: /project/public/i18n/en
322
+ * → namespace: 'settings' (index is stripped)
323
+ */
324
+ export function getNamespaceFromPath(filePath: string, localeDir: string): string {
325
+ // Get relative path from locale directory
326
+ const relative = path.relative(localeDir, filePath);
327
+
328
+ // Remove .json extension
329
+ const withoutExt = relative.replace(/\.json$/i, '');
330
+
331
+ // Convert path separators to dots
332
+ const namespace = withoutExt.replace(/[\\/]/g, '.');
333
+
334
+ // Remove trailing .index (index.json files represent the folder itself)
335
+ return namespace.replace(/\.index$/, '');
336
+ }
337
+
338
+ /**
339
+ * Wrap a translation object with its namespace.
340
+ *
341
+ * Example:
342
+ * - namespace: 'auth.login'
343
+ * - content: { title: 'Welcome', subtitle: 'Login here' }
344
+ * - result: { auth: { login: { title: 'Welcome', subtitle: 'Login here' } } }
345
+ */
346
+ export function wrapWithNamespace(
347
+ namespace: string,
348
+ content: Record<string, unknown>
349
+ ): Record<string, unknown> {
350
+ if (!namespace) return content;
351
+
352
+ const parts = namespace.split('.');
353
+ let result: Record<string, unknown> = content;
354
+
355
+ // Build from inside out
356
+ for (let i = parts.length - 1; i >= 0; i--) {
357
+ result = { [parts[i]]: result };
358
+ }
359
+
360
+ return result;
361
+ }
362
+
363
+ /**
364
+ * Generate code that wraps imported content with namespace at runtime.
365
+ * Used in virtual module generation.
366
+ */
367
+ export function generateNamespaceWrapperCode(): string {
368
+ return `
369
+ function __wrapWithNamespace(namespace, content) {
370
+ if (!namespace) return content;
371
+ const parts = namespace.split('.');
372
+ let result = content;
373
+ for (let i = parts.length - 1; i >= 0; i--) {
374
+ result = { [parts[i]]: result };
375
+ }
376
+ return result;
377
+ }`;
378
+ }