vbss-translator 1.1.2 → 2.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Vitor Bastos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -7,6 +7,7 @@ A lightweight React translation toolkit focused on ergonomics, sensible defaults
7
7
  Help us keep vbss-translator free and maintained:
8
8
 
9
9
  - Buy me a coffee: [buymeacoffee.com/vbss.io](https://www.buymeacoffee.com/vbss.io)
10
+ - GitHub Sponsors: [github.com/sponsors/vbss-io](https://github.com/sponsors/vbss-io)
10
11
  - Star on GitHub: [github.com/vbss-io/vbss-translator](https://github.com/vbss-io/vbss-translator)
11
12
  - Share the tool: [ui.vbss.io/tools/vbss-translator](https://ui.vbss.io/tools/vbss-translator)
12
13
 
@@ -164,7 +165,7 @@ const externalTranslation = {
164
165
  | Field | Type | Default | Notes |
165
166
  | --- | --- | --- | --- |
166
167
  | `enabled` | `boolean` | `false` | Master switch for the entire pipeline. |
167
- | `timeoutMs` | `number` | `5_000` | Max duration before aborting a request. Exposed to provider via `AbortController`. |
168
+ | `timeoutMs` | `number` | `5_000` | Max duration before aborting a request. Exposed to provider via `AbortController`. Enforced even when the provider ignores the signal: the request fails as a timeout (reported through `onTranslationError`), the original text is kept and the same key can be requested again. |
168
169
  | `debug` | `boolean` | `false` | Emits structured logs for cache hits, deduped requests, retries, etc. |
169
170
  | `provider` | `ProviderConfig` | `{ id: "google" }` | Google or custom provider config. See provider sections below. |
170
171
  | `cache` | `CacheConfig` | `{ enabled: false, ttlMs: 3_600_000 }` | In-memory cache with TTL and optional LRU size limit (`maxEntries`). |
@@ -177,6 +178,7 @@ const externalTranslation = {
177
178
  ### Provider Behaviour
178
179
 
179
180
  - The Google provider (`src/external/providers/googleTranslateProvider.ts`) constructs REST calls to the v2 API, supports Glossaries, forwards custom headers, and normalizes errors (incl. retryable codes).
181
+ - The Google provider reports unavailable when it has no `apiKey`, no non-empty `headers` and no custom `endpoint`; `TranslatorProvider` then emits the `TranslatorProvider_provider_unavailable` warning. The availability check only runs when `externalTranslation.enabled` is `true`.
180
182
  - Providers may implement `normalizeError` to produce structured failures consumed by the manager.
181
183
  - `ExternalTranslationManager` dedupes identical requests, enforces `timeoutMs`, respects `AbortSignal`, handles cache reads/writes, and never throws back into your components. All errors are converted into loggable events and surfaced via callbacks.
182
184
 
@@ -436,13 +438,28 @@ npx vbss-translator generate [--pattern <glob>] [--output <path>] [--format <ts|
436
438
  | --- | --- | --- |
437
439
  | `--pattern` | Glob for JSON sources. Resolved relative to `process.cwd()`. | `src/**/translations.json` |
438
440
  | `--output` | Output file path. Parent directories are created automatically. | `src/translations/index.ts` |
439
- | `--format` | Output format (`ts`, `js`, or `tsx`). | `ts` |
441
+ | `--format` | Output format (`ts`, `js`, or `tsx`). Any other value exits with code `1` and lists the accepted formats, without generating a file. | `ts` |
440
442
  | `--reference-language` | Language key used for deduplication. | First language in the first valid file |
441
443
  | `--config` | Path to `vbss-translator.config.json`. | Project root |
442
- | `--watch`, `-w` | Watch mode with regeneration + debug logs. | Disabled |
444
+ | `--watch`, `-w` | Watch mode with regeneration. | Disabled |
443
445
 
444
446
  Order of precedence: **CLI flags > config file > defaults**. Config parsing is performed by `src/cli/config.ts`.
445
447
 
448
+ ### Pattern Syntax
449
+
450
+ `--pattern` (and `pattern` in the config file) uses a small built-in matcher, not the full `glob` package syntax:
451
+
452
+ - `*` matches any run of characters inside one path segment, `?` matches exactly one character.
453
+ - `**` as a whole segment matches zero or more directories.
454
+ - `[abc]`, `[a-z]`, `[!abc]` and `[^abc]` match one character from (or outside) the set.
455
+ - `{a,b}` expands to alternatives and can be nested (`src/{app,lib}/**/translations.json`).
456
+ - Absolute patterns are supported; results are returned in sorted order.
457
+ - Dot files and dot directories are only matched by a segment that itself starts with `.`; `**` never enters them.
458
+ - `**` does not follow symlinked or junction directories; a single-level segment (`linked-*/translations.json`) does.
459
+ - Backslashes are treated as path separators, so they cannot escape special characters.
460
+ - Not supported: extglobs (`@(a|b)`), numeric brace ranges (`{1..3}`) and POSIX classes (`[[:alpha:]]`). The default `src/**/translations.json` and the other patterns used by the projects that consume this CLI only need the forms above.
461
+ - Matching is case-insensitive on Windows and macOS, case-sensitive elsewhere.
462
+
446
463
  ### Output Formats
447
464
 
448
465
  - **ts / tsx**: Imports each JSON file with `assert { type: "json" }`, exports a `Translation` interface, merges arrays (wrapping standalone objects), dedupes using the reference language, and default-exports `uniqueTranslations`.
@@ -467,7 +484,6 @@ Generation fails fast when validation errors occur; exit code `2` signals schema
467
484
  - Uses native `fs.watch` with glob filtering to detect additions, changes, and deletions.
468
485
  - Debounces rapid changes (300ms) and regenerates the output file.
469
486
  - Keeps running until interrupted. Clean-up handlers close watchers on `SIGINT`/`SIGTERM`.
470
- - Emits verbose debug logs to help diagnose path matching.
471
487
 
472
488
  ### Programmatic API
473
489
 
@@ -518,6 +534,33 @@ Rules enforced by the generator:
518
534
 
519
535
  ---
520
536
 
537
+ ## Publishing
538
+
539
+ Releases are published manually (there is no CI in this repository) and only through the release script:
540
+
541
+ ```bash
542
+ npm run release:dry -- patch # rehearsal: gates, version, publish --dry-run, repository restored
543
+ npm run release -- patch --yes-publish # real release (or minor / major)
544
+ npm run patch-deploy -- --yes-publish # same as above (or minor-deploy / major-deploy)
545
+ ```
546
+
547
+ A real release only starts with the explicit `--yes-publish` argument; without it the script refuses before doing anything. The bump and the flags are accepted in any order. Dry mode is also detected when npm swallows the flag (`npm run release patch --dry-run` without `--` sets `npm_config_dry_run`), so that mistyped form stays a dry run and never becomes a real release. Always keep the `--` before the script arguments. The script prints the package and version it is about to publish.
548
+
549
+ `.npmrc` sets `ignore-scripts=true` as supply-chain protection, so npm never runs `prepublishOnly` on its own. `scripts/release.mjs` therefore runs the whole release in a single process:
550
+
551
+ 1. Refuses a dirty working tree.
552
+ 2. `npm run verify` (lint, typecheck, jest with the global 90/80/90/90 thresholds, the per-file 80 check in `scripts/coverage-per-file.mjs`, lock-guard, audit-gate and, as the last step, build). Any failure stops the release before the version bump. Because the build is the last step, the `dist/` fingerprint is taken right after the build.
553
+ 3. `npm version <bump>`, then confirms the version commit only touched `package.json`/`package-lock.json`.
554
+ 4. Confirms `dist/` is byte-identical to what verify built, then `npm publish`.
555
+
556
+ If the script refuses after the version step (including a missing `dist/`), it undoes only what it created: it deletes the tag it made and runs `git reset --keep` back to the pre-release commit, then reports. Once `npm publish` has started nothing is undone, so check the registry before anything else. Do not edit files while a release runs: the tree is proven clean before versioning and the cleanup assumes nothing else changes it.
557
+
558
+ `--dry-run` runs the same gates, bumps the version without committing (restored afterwards) and ends in `npm publish --dry-run`.
559
+
560
+ Do not run a bare `npm publish`: with `ignore-scripts=true` npm skips `prepublishOnly`, and with scripts enabled it refuses unless `VBSS_RELEASE=1`, which only `scripts/release.mjs` sets.
561
+
562
+ ---
563
+
521
564
  ## Debugging & Best Practices
522
565
 
523
566
  - Enable `externalTranslation.debug` during development to track cache hits, deduped requests, vetoes, and timing information. Logs are tagged with `[vbss-translator]`.
package/dist/cli/index.js CHANGED
@@ -1,43 +1,43 @@
1
1
  #!/usr/bin/env node
2
- import{dirname as w,resolve as d,normalize as p,relative as $}from"path";import{glob as T}from"glob";import{mkdir as G,writeFile as O,readFile as F}from"fs/promises";import{watch as U,existsSync as _}from"fs";async function x(o){try{const t=await T(o,{cwd:process.cwd(),absolute:!1}),e=process.cwd();return t.map(n=>({path:d(e,n),relativePath:p(n).replace(/\\/g,"/"),translations:[]}))}catch(t){const e=t instanceof Error?t.message:"Unknown error";return[{path:"",relativePath:"",translations:[],error:{file:o,message:`Failed to discover files: ${e}`,type:"file_system"}}]}}async function j(o){const t=o.map(async e=>{if(e.error)return e;try{const n=await F(e.path,"utf-8"),s=JSON.parse(n),a=[];if(Array.isArray(s))for(const r of s){if(typeof r!="object"||r===null)return{...e,translations:[],error:{file:e.path,message:"Translation array must contain objects only",type:"validation"}};const u={};for(const[l,i]of Object.entries(r)){if(typeof i!="string")return{...e,translations:[],error:{file:e.path,message:`Translation value for key "${l}" must be a string, got ${typeof i}`,type:"validation"}};u[l]=i}a.push(u)}else if(typeof s=="object"&&s!==null){const r={};for(const[u,l]of Object.entries(s)){if(typeof l!="string")return{...e,translations:[],error:{file:e.path,message:`Translation value for key "${u}" must be a string, got ${typeof l}`,type:"validation"}};r[u]=l}return a.push(r),{...e,translations:a,wasSingleObject:!0}}else return{...e,translations:[],error:{file:e.path,message:"Translation file must contain a JSON object or array of objects",type:"validation"}};return{...e,translations:a}}catch(n){if(n instanceof SyntaxError)return{...e,translations:[],error:{file:e.path,message:`Invalid JSON: ${n.message}`,type:"invalid_json"}};const s=n instanceof Error?n.message:"Unknown error";return{...e,translations:[],error:{file:e.path,message:`Failed to read file: ${s}`,type:"file_system"}}}});return Promise.all(t)}function S(o){for(const t of o)if(!t.error&&t.translations.length>0)return Object.keys(t.translations[0]);return null}function B(o,t){const e=[];for(const n of o){if(n.error)continue;if(n.translations.length===0){e.push({file:n.path,message:"File has no translations",type:"validation"});continue}const s=Object.keys(n.translations[0]);for(let i=1;i<n.translations.length;i++){const f=Object.keys(n.translations[i]);if(JSON.stringify([...f].sort())!==JSON.stringify([...s].sort())){e.push({file:n.path,message:`Translation ${i+1} in file has different language keys`,type:"validation"});continue}}const a=[...s].sort(),r=[...t].sort(),u=r.filter(i=>!a.includes(i)),l=a.filter(i=>!r.includes(i));if(u.length>0||l.length>0){const i=[];u.length>0&&i.push(`missing languages: ${u.join(", ")}`),l.length>0&&i.push(`extra languages: ${l.join(", ")}`),e.push({file:n.path,message:`Language mismatch: ${i.join(", ")}. Expected: ${t.join(", ")}`,type:"missing_languages"})}}return e}function k(o,t){const e=new Set,n=[];for(const s of o){const a=s[t];if(a===void 0){n.push(s);continue}const r=a;e.has(r)||(e.add(r),n.push(s))}return n}function L(o,t){const e=w(o);let s=$(e,t);return s=p(s).replace(/\\/g,"/"),s.startsWith(".")||(s="./"+s),s}function P(o,t,e){const n=o.filter(f=>!f.error&&f.translations.length>0).sort((f,h)=>f.path.localeCompare(h.path));if(n.length===0)return`export default []
3
- `;const s=n.map((f,h)=>{const c=L(t,f.path);return`import translations${h} from '${c}' assert { type: 'json' };`}).join(`
4
- `),a=n.map((f,h)=>f.wasSingleObject?` ...(Array.isArray(translations${h}) ? translations${h} : [translations${h}])`:` ...translations${h}`).join(`,
5
- `),u=`export interface Translation {
6
- ${e.map(f=>` ${f}: string;`).join(`
2
+ import{isAbsolute as L,parse as I,resolve as w,join as y,dirname as T,normalize as m,relative as C}from"path";import{readdir as J,stat as B,mkdir as z,writeFile as q,readFile as W}from"fs/promises";import{watch as V,existsSync as H}from"fs";const K=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"]),R=new Set(["win32","darwin"]),A=n=>typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string"&&K.has(n.code),k=async n=>{try{return await J(n,{withFileTypes:!0})}catch(t){if(A(t))return[];throw t}},O=async n=>{try{return await B(n)}catch(t){if(A(t))return null;throw t}},X=n=>n.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&"),Y=n=>n.replace(/[\\\][^]/g,"\\$&"),Q=(n,t)=>{const e=[];let r=0,s=t+1;for(let o=t;o<n.length;o++){const a=n[o];if(a==="{")r++;else if(a==="}"){if(r--,r===0)return e.push(n.slice(s,o)),{alternatives:e,end:o}}else a===","&&r===1&&(e.push(n.slice(s,o)),s=o+1)}return{alternatives:e,end:-1}},b=n=>{const t=n.indexOf("{");if(t===-1)return[n];const{alternatives:e,end:r}=Q(n,t);if(r===-1)return[n];const s=n.slice(0,t),o=n.slice(r+1);if(e.length<2){const a=n.slice(t,r+1);return b(o).map(i=>s+a+i)}return e.flatMap(a=>b(s+a+o))},Z=(n,t)=>{let e="";for(let r=0;r<n.length;r++){const s=n[r];if(s==="*")e+="[^/]*";else if(s==="?")e+="[^/]";else if(s==="["){const o=n.indexOf("]",r+2);if(o===-1)e+="\\[";else{const a=n.slice(r+1,o),i=a.startsWith("!")||a.startsWith("^");e+=`[${i?"^":""}${Y(i?a.slice(1):a)}]`,r=o}}else e+=X(s)}return new RegExp(`^${e}$`,t?"i":"")},N=(n,t)=>{const e=[];for(const r of n)r==="**"?e[e.length-1]?.kind!=="globstar"&&e.push({kind:"globstar"}):/[*?[]/.test(r)?e.push({kind:"pattern",regexp:Z(r,t),matchesDotfiles:r.startsWith(".")}):e.push({kind:"literal",text:r});return e},tt=(n,t,e)=>n.kind==="literal"?e?n.text.toLowerCase()===t.toLowerCase():n.text===t:t.startsWith(".")&&!n.matchesDotfiles?!1:n.regexp.test(t),E=(n,t,e,r,s)=>{const o=n[t];if(!o)return r===e.length;if(o.kind!=="globstar")return r<e.length&&tt(o,e[r],s)&&E(n,t+1,e,r+1,s);if(t===n.length-1)return r<e.length&&e.slice(r).every(i=>!i.startsWith("."));for(let i=r;i<=e.length;i++){if(i>r&&e[i-1].startsWith("."))return!1;if(E(n,t+1,e,i,s))return!0}return!1},x=n=>n.replace(/\\/g,"/").split("/").filter(t=>t!==""&&t!=="."),et=(n,t)=>{const e=R.has(process.platform),r=x(n);return b(t.replace(/\\/g,"/")).some(s=>{const o=x(s);return o.length===0?!1:E(N(o,e),0,r,0,e)})},D=async(n,t)=>t.isFile()?!0:t.isSymbolicLink()?(await O(y(n,t.name)))?.isFile()??!1:!1,nt=async(n,t)=>t.isDirectory()?!0:t.isSymbolicLink()?(await O(y(n,t.name)))?.isDirectory()??!1:!1;async function _(n,t){const e=R.has(process.platform),r=new Set;for(const s of b(n.replace(/\\/g,"/"))){const o=L(s)?I(s).root:"",a=s.slice(o.length).split("/").filter(l=>l!==""&&l!==".");if(a.length===0)continue;const i=N(a,e),f=(l,g,u)=>{r.add(o||t.absolute?w(l,u):[...g,u].join("/"))},c=async(l,g,u)=>{const d=i[u],$=u===i.length-1;if(d.kind==="globstar"){$||await c(l,g,u+1);for(const p of await k(l))p.name.startsWith(".")||(p.isDirectory()?await c(y(l,p.name),[...g,p.name],u):$&&await D(l,p)&&f(l,g,p.name));return}if(d.kind==="literal"){const p=y(l,d.text),v=await O(p);if(!v)return;$?v.isFile()&&f(l,g,d.text):v.isDirectory()&&await c(p,[...g,d.text],u+1);return}for(const p of await k(l))d.regexp.test(p.name)&&(p.name.startsWith(".")&&!d.matchesDotfiles||($?await D(l,p)&&f(l,g,p.name):await nt(l,p)&&await c(y(l,p.name),[...g,p.name],u+1)))};await c(o||w(t.cwd),[],0)}return[...r].sort()}async function rt(n){try{const t=await _(n,{cwd:process.cwd(),absolute:!1}),e=process.cwd();return t.map(r=>({path:w(e,r),relativePath:m(r).replace(/\\/g,"/"),translations:[]}))}catch(t){const e=t instanceof Error?t.message:"Unknown error";return[{path:"",relativePath:"",translations:[],error:{file:n,message:`Failed to discover files: ${e}`,type:"file_system"}}]}}async function st(n){const t=n.map(async e=>{if(e.error)return e;try{const r=await W(e.path,"utf-8"),s=JSON.parse(r),o=[];if(Array.isArray(s))for(const a of s){if(typeof a!="object"||a===null)return{...e,translations:[],error:{file:e.path,message:"Translation array must contain objects only",type:"validation"}};const i={};for(const[f,c]of Object.entries(a)){if(typeof c!="string")return{...e,translations:[],error:{file:e.path,message:`Translation value for key "${f}" must be a string, got ${typeof c}`,type:"validation"}};i[f]=c}o.push(i)}else if(typeof s=="object"&&s!==null){const a={};for(const[i,f]of Object.entries(s)){if(typeof f!="string")return{...e,translations:[],error:{file:e.path,message:`Translation value for key "${i}" must be a string, got ${typeof f}`,type:"validation"}};a[i]=f}return o.push(a),{...e,translations:o,wasSingleObject:!0}}else return{...e,translations:[],error:{file:e.path,message:"Translation file must contain a JSON object or array of objects",type:"validation"}};return{...e,translations:o}}catch(r){if(r instanceof SyntaxError)return{...e,translations:[],error:{file:e.path,message:`Invalid JSON: ${r.message}`,type:"invalid_json"}};const s=r instanceof Error?r.message:"Unknown error";return{...e,translations:[],error:{file:e.path,message:`Failed to read file: ${s}`,type:"file_system"}}}});return Promise.all(t)}function at(n){for(const t of n)if(!t.error&&t.translations.length>0)return Object.keys(t.translations[0]);return null}function ot(n,t){const e=[];for(const r of n){if(r.error)continue;if(r.translations.length===0){e.push({file:r.path,message:"File has no translations",type:"validation"});continue}const s=Object.keys(r.translations[0]);for(let c=1;c<r.translations.length;c++){const l=Object.keys(r.translations[c]);if(JSON.stringify([...l].sort())!==JSON.stringify([...s].sort())){e.push({file:r.path,message:`Translation ${c+1} in file has different language keys`,type:"validation"});continue}}const o=[...s].sort(),a=[...t].sort(),i=a.filter(c=>!o.includes(c)),f=o.filter(c=>!a.includes(c));if(i.length>0||f.length>0){const c=[];i.length>0&&c.push(`missing languages: ${i.join(", ")}`),f.length>0&&c.push(`extra languages: ${f.join(", ")}`),e.push({file:r.path,message:`Language mismatch: ${c.join(", ")}. Expected: ${t.join(", ")}`,type:"missing_languages"})}}return e}function it(n,t){const e=new Set,r=[];for(const s of n){const o=s[t];if(o===void 0){r.push(s);continue}const a=o;e.has(a)||(e.add(a),r.push(s))}return r}function ct(n,t){const e=T(n);let s=C(e,t);return s=m(s).replace(/\\/g,"/"),s.startsWith(".")||(s="./"+s),s}function G(n,t,e){const r=n.filter(l=>!l.error&&l.translations.length>0).sort((l,g)=>l.path.localeCompare(g.path));if(r.length===0)return`export default []
3
+ `;const s=r.map((l,g)=>{const u=ct(t,l.path);return`import translations${g} from '${u}' assert { type: 'json' };`}).join(`
4
+ `),o=r.map((l,g)=>l.wasSingleObject?` ...(Array.isArray(translations${g}) ? translations${g} : [translations${g}])`:` ...translations${g}`).join(`,
5
+ `),i=`export interface Translation {
6
+ ${e.map(l=>` ${l}: string;`).join(`
7
7
  `)}
8
8
  [key: string]: string;
9
- }`,l=e[0]||"en",i=n.length>0?`
9
+ }`,f=e[0]||"en",c=r.length>0?`
10
10
  const uniqueTranslations = allTranslations.filter(
11
- (translation, index, self) => index === self.findIndex((t) => t.${l} === translation.${l})
11
+ (translation, index, self) => index === self.findIndex((t) => t.${f} === translation.${f})
12
12
  );`:"";return`${s}
13
13
 
14
- ${u}
14
+ ${i}
15
15
 
16
16
  const allTranslations: Translation[] = [
17
- ${a}
18
- ];${i}
17
+ ${o}
18
+ ];${c}
19
19
 
20
20
  export default uniqueTranslations;
21
- `}function A(o){const t=o.filter(r=>!r.error&&r.translations.length>0).sort((r,u)=>r.path.localeCompare(u.path));if(t.length===0)return`export default []
22
- `;const e=[];for(const r of t)r.wasSingleObject&&r.translations.length===1?e.push(r.translations[0]):e.push(...r.translations);const n=e.length>0?Object.keys(e[0])[0]:"en",s=e.map(r=>JSON.stringify(r,null,2).split(`
23
- `).map(i=>` ${i}`).join(`
21
+ `}function lt(n){const t=n.filter(a=>!a.error&&a.translations.length>0).sort((a,i)=>a.path.localeCompare(i.path));if(t.length===0)return`export default []
22
+ `;const e=[];for(const a of t)a.wasSingleObject&&a.translations.length===1?e.push(a.translations[0]):e.push(...a.translations);const r=e.length>0?Object.keys(e[0])[0]:"en",s=e.map(a=>JSON.stringify(a,null,2).split(`
23
+ `).map(c=>` ${c}`).join(`
24
24
  `)).join(`,
25
- `),a=`
25
+ `),o=`
26
26
  const uniqueTranslations = allTranslations.filter(
27
- (translation, index, self) => index === self.findIndex((t) => t.${n} === translation.${n})
27
+ (translation, index, self) => index === self.findIndex((t) => t.${r} === translation.${r})
28
28
  );`;return`const allTranslations = [
29
29
  ${s}
30
- ];${a}
30
+ ];${o}
31
31
 
32
32
  export default uniqueTranslations;
33
- `}function C(o,t,e){return P(o,t,e)}async function E(o){const t=[],e=Date.now(),n=await x(o.pattern);if(n.length===0)return{success:!0,filesFound:0,translationsGenerated:0,errors:[],outputPath:o.outputPath};for(const c of n)c.error&&t.push(c.error);const s=await j(n);for(const c of s)c.error&&t.push(c.error);const a=S(s);if((!a||a.length===0)&&s.filter(m=>!m.error&&m.translations.length>0).length===0)return{success:!1,filesFound:n.length,translationsGenerated:0,errors:t.length>0?t:[{file:o.pattern,message:"No valid translation files found",type:"validation"}],outputPath:o.outputPath};if(a&&a.length>0){const c=B(s,a);if(t.push(...c),c.length>0)return{success:!1,filesFound:n.length,translationsGenerated:0,errors:t,outputPath:o.outputPath}}const r=[];for(const c of s)!c.error&&c.translations.length>0&&r.push(...c.translations);const u=o.referenceLanguage||a?.[0]||"en",l=k(r,u);let i;const f=s.filter(c=>!c.error&&c.translations.length>0);switch(o.outputFormat){case"ts":i=P(f,o.outputPath,a||[]);break;case"tsx":i=C(f,o.outputPath,a||[]);break;case"js":i=A(f);break;default:return{success:!1,filesFound:n.length,translationsGenerated:0,errors:[...t,{file:o.outputPath,message:`Unsupported output format: ${o.outputFormat}`,type:"validation"}],outputPath:o.outputPath}}try{const c=w(o.outputPath);await G(c,{recursive:!0}),await O(o.outputPath,i,"utf-8")}catch(c){const m=c instanceof Error?c.message:"Unknown error";return t.push({file:o.outputPath,message:`Failed to write output file: ${m}`,type:"file_system"}),{success:!1,filesFound:n.length,translationsGenerated:l.length,errors:t,outputPath:o.outputPath}}const h=Date.now()-e;return h>1e3&&n.length<100&&console.warn(`⚠️ Generation took ${h}ms for ${n.length} files`),{success:t.length===0,filesFound:n.length,translationsGenerated:l.length,errors:t,outputPath:o.outputPath}}const R="src/**/translations.json",W="src/translations/index.ts",N="ts";class I{async loadFromFile(t){try{const e=d(t),n=await F(e,"utf-8");return JSON.parse(n)}catch(e){if(e&&typeof e=="object"&&"code"in e&&e.code==="ENOENT")return null;throw e instanceof SyntaxError?new Error(`Invalid JSON in config file: ${e.message}`):e}}loadFromArgs(t){const e={};return typeof t.pattern=="string"&&(e.pattern=t.pattern),typeof t.output=="string"&&(e.outputPath=t.output),typeof t.format=="string"&&(t.format==="ts"||t.format==="js"||t.format==="tsx")&&(e.outputFormat=t.format),typeof t["reference-language"]=="string"&&(e.referenceLanguage=t["reference-language"]),e}merge(t,e){const n={...t,...e};return{pattern:n.pattern??R,outputPath:n.outputPath??W,outputFormat:n.outputFormat??N,referenceLanguage:n.referenceLanguage}}}const y=new I,D=300;function J(o,t,e){try{const n=p(o),s=p(e);let a;try{a=$(s,n)}catch{a=$(e,o)}a=a.replace(/\\/g,"/");let r=t.replace(/\\/g,"/");r=r.replace(/\*\*\//g,"___GLOB_DOUBLE_STAR_SLASH___"),r=r.replace(/\*\*/g,"___GLOB_DOUBLE_STAR___"),r=r.replace(/\./g,"\\."),r=r.replace(/\*/g,"[^/]*"),r=r.replace(/\?/g,"[^/]"),r=r.replace(/___GLOB_DOUBLE_STAR_SLASH___/g,"(.*/)?"),r=r.replace(/___GLOB_DOUBLE_STAR___/g,".*");const l=new RegExp(`^${r}$`).test(a);return console.log(`[DEBUG] Pattern matching: "${a}" against "${r}" = ${l}`),l}catch(n){console.log("[DEBUG] Pattern matching failed, using fallback:",n);const s=$(e,o).replace(/\\/g,"/"),a=s.split("/"),r=a[a.length-1]==="translations.json"&&a[0]==="src";return console.log(`[DEBUG] Fallback pattern matching: "${s}" = ${r}`),r}}function M(o){const t=new Set;for(const e of o)t.add(w(e));return Array.from(t)}class z{watchers=new Map;debounceTimer=null;isWatching=!1;generatorOptions=null;callback=null;pattern="";cwd="";async watch(t,e){if(this.isWatching)throw new Error("Watch service is already watching");this.pattern=t,this.callback=e,this.cwd=p(process.cwd()),this.isWatching=!0;const n=await T(t,{cwd:this.cwd,absolute:!0}),s=M(n);s.length===0&&s.push(this.cwd);const a=s.map(u=>p(u));console.log(`[DEBUG] Watching ${a.length} directory(ies) for pattern: ${t}`);for(const u of a)console.log(`[DEBUG] Setting up watch for directory: ${u}`),this.watchDirectory(u);const r=p(this.cwd);this.watchers.has(r)||(console.log(`[DEBUG] Setting up watch for root directory: ${r}`),this.watchDirectory(r)),console.log(`[DEBUG] Total watchers active: ${this.watchers.size}`)}watchDirectory(t){const e=p(t);if(this.watchers.has(e)){console.log(`[DEBUG] Already watching directory: ${e}`);return}console.log(`[DEBUG] Starting watch on directory: ${e}`);const n=U(e,{recursive:!0},(s,a)=>{if(!a){console.log(`[DEBUG] Event received but filename is empty, eventType: ${s}`);return}console.log(`[DEBUG] File system event: ${s} on ${a} in ${e}`);let r;try{r=d(e,a),r=p(r)}catch{r=p(a)}console.log(`[DEBUG] Resolved file path: ${r}`),console.log(`[DEBUG] Pattern: ${this.pattern}, CWD: ${this.cwd}`);const u=J(r,this.pattern,this.cwd);if(console.log(`[DEBUG] Pattern match result: ${u}`),!u){console.log(`[DEBUG] File does not match pattern, ignoring: ${r}`);return}console.log("[DEBUG] File matches pattern! Processing event...");let l;if(s==="rename"){const i=_(r);l=i?"add":"delete",console.log(`[DEBUG] Rename event, file exists: ${i}, normalized to: ${l}`)}else s==="change"?(l="change",console.log("[DEBUG] Change event detected")):(l="change",console.log(`[DEBUG] Unknown event type: ${s}, defaulting to change`));if(l==="add"){const i=w(r),f=p(i);!this.watchers.has(f)&&f!==e&&(console.log(`[DEBUG] New file detected, ensuring directory is watched: ${f}`),this.watchDirectory(f))}console.log(`[DEBUG] Triggering regeneration for: ${r} (${l})`),this.debounceRegeneration(r,l)});this.watchers.set(e,n),n.on("error",s=>{console.error(`[DEBUG] Watch error in ${e}:`,s)}),console.log(`[DEBUG] Watch successfully set up for: ${e}`)}debounceRegeneration(t,e){console.log(`[DEBUG] debounceRegeneration called for: ${t} (${e})`),this.debounceTimer&&(console.log("[DEBUG] Clearing existing debounce timer"),clearTimeout(this.debounceTimer)),console.log(`[DEBUG] Setting new debounce timer (${D}ms)`),this.debounceTimer=setTimeout(async()=>{if(console.log("[DEBUG] Debounce timer fired, starting regeneration..."),!this.generatorOptions||!this.callback){console.log("[DEBUG] Missing generatorOptions or callback, aborting regeneration");return}try{console.log("[DEBUG] Calling generate with options:",{pattern:this.generatorOptions.pattern,outputPath:this.generatorOptions.outputPath,outputFormat:this.generatorOptions.outputFormat});const n=await E(this.generatorOptions),s=e;this.callback&&this.callback({type:s,file:t}),n.success?console.log(`✅ Regenerated translations (${n.translationsGenerated} translations from ${n.filesFound} file(s))`):console.error(`❌ Regeneration failed: ${n.errors.map(a=>a.message).join(", ")}`)}catch(n){const s=n instanceof Error?n.message:"Unknown error";console.error(`❌ Watch regeneration error: ${s}`)}},D)}setGeneratorOptions(t){this.generatorOptions=t}stop(){if(this.isWatching){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null);for(const[,t]of this.watchers.entries())t.close();this.watchers.clear(),this.isWatching=!1,this.generatorOptions=null,this.callback=null}}}async function q(o){const t=new z;t.setGeneratorOptions(o),console.log("🔍 Watching for translation file changes...");const e=await E(o);e.success?console.log(`✅ Initial generation: ${e.translationsGenerated} translations from ${e.filesFound} file(s)`):console.error(`❌ Initial generation failed: ${e.errors.map(s=>s.message).join(", ")}`),await t.watch(o.pattern,()=>{});const n=()=>{console.log(`
34
- 👋 Stopping watch mode...`),t.stop(),process.exit(0)};return process.on("SIGINT",n),process.on("SIGTERM",n),new Promise(()=>{})}var H={};const g={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m"},b={searching:"🔍",success:"✅",error:"❌"};function V(o){const t={};let e=0;for(;e<o.length;){const n=o[e];if(n.startsWith("--")&&n.includes("=")){const[s,...a]=n.slice(2).split("="),r=a.join("=");t[s]=r||!0,e++;continue}if(n.startsWith("--")){const s=n.slice(2);e+1<o.length&&!o[e+1].startsWith("--")?(t[s]=o[e+1],e+=2):(t[s]=!0,e++);continue}if(n.startsWith("-")&&!n.startsWith("--")){const s=n.slice(1);t[s]=!0,e++;continue}e++}return t}function K(){const o=`
35
- ${g.blue}vbss-translator generate${g.reset}
33
+ `}function ut(n,t,e){return G(n,t,e)}async function S(n){const t=[],e=Date.now(),r=await rt(n.pattern);if(r.length===0)return{success:!0,filesFound:0,translationsGenerated:0,errors:[],outputPath:n.outputPath};const s=await st(r);for(const u of s)u.error&&t.push(u.error);const o=at(s);if((!o||o.length===0)&&s.filter(d=>!d.error&&d.translations.length>0).length===0)return{success:!1,filesFound:r.length,translationsGenerated:0,errors:t.length>0?t:[{file:n.pattern,message:"No valid translation files found",type:"validation"}],outputPath:n.outputPath};if(o&&o.length>0){const u=ot(s,o);if(t.push(...u),u.length>0)return{success:!1,filesFound:r.length,translationsGenerated:0,errors:t,outputPath:n.outputPath}}const a=[];for(const u of s)!u.error&&u.translations.length>0&&a.push(...u.translations);const i=n.referenceLanguage||o?.[0]||"en",f=it(a,i);let c;const l=s.filter(u=>!u.error&&u.translations.length>0);switch(n.outputFormat){case"ts":c=G(l,n.outputPath,o||[]);break;case"tsx":c=ut(l,n.outputPath,o||[]);break;case"js":c=lt(l);break;default:return{success:!1,filesFound:r.length,translationsGenerated:0,errors:[...t,{file:n.outputPath,message:`Unsupported output format: ${n.outputFormat}`,type:"validation"}],outputPath:n.outputPath}}try{const u=T(n.outputPath);await z(u,{recursive:!0}),await q(n.outputPath,c,"utf-8")}catch(u){const d=u instanceof Error?u.message:"Unknown error";return t.push({file:n.outputPath,message:`Failed to write output file: ${d}`,type:"file_system"}),{success:!1,filesFound:r.length,translationsGenerated:f.length,errors:t,outputPath:n.outputPath}}const g=Date.now()-e;return g>1e3&&r.length<100&&console.warn(`⚠️ Generation took ${g}ms for ${r.length} files`),{success:t.length===0,filesFound:r.length,translationsGenerated:f.length,errors:t,outputPath:n.outputPath}}const ft="src/**/translations.json",ht="src/translations/index.ts",gt="ts",U=["ts","js","tsx"];class M extends Error{constructor(t){super(t),this.name="CliUsageError"}}const pt=n=>U.some(t=>t===n);class dt{async loadFromFile(t){try{const e=w(t),r=await W(e,"utf-8");return JSON.parse(r)}catch(e){if(e&&typeof e=="object"&&"code"in e&&e.code==="ENOENT")return null;throw e instanceof SyntaxError?new Error(`Invalid JSON in config file: ${e.message}`):e}}loadFromArgs(t){const e={};if(typeof t.pattern=="string"&&(e.pattern=t.pattern),typeof t.output=="string"&&(e.outputPath=t.output),typeof t.format=="string"){if(!pt(t.format))throw new M(`Invalid --format value "${t.format}". Accepted formats: ${U.join(", ")}`);e.outputFormat=t.format}return typeof t["reference-language"]=="string"&&(e.referenceLanguage=t["reference-language"]),e}merge(t,e){const r={...t,...e};return{pattern:r.pattern??ft,outputPath:r.outputPath??ht,outputFormat:r.outputFormat??gt,referenceLanguage:r.referenceLanguage}}}const F=new dt,mt=300;function wt(n,t,e){const r=L(t)?n:C(e,n);return et(r,t)}function yt(n){const t=new Set;for(const e of n)t.add(T(e));return Array.from(t)}class $t{watchers=new Map;debounceTimer=null;isWatching=!1;generatorOptions=null;callback=null;pattern="";cwd="";async watch(t,e){if(this.isWatching)throw new Error("Watch service is already watching");this.pattern=t,this.callback=e,this.cwd=m(process.cwd()),this.isWatching=!0;const r=await _(t,{cwd:this.cwd,absolute:!0}),s=yt(r);s.length===0&&s.push(this.cwd);const o=s.map(i=>m(i));for(const i of o)this.watchDirectory(i);const a=m(this.cwd);this.watchers.has(a)||this.watchDirectory(a)}watchDirectory(t){const e=m(t);if(this.watchers.has(e))return;const r=V(e,{recursive:!0},(s,o)=>{if(!o)return;let a;try{a=w(e,o),a=m(a)}catch{a=m(o)}if(!wt(a,this.pattern,this.cwd))return;let f;if(s==="rename"?f=H(a)?"add":"delete":f="change",f==="add"){const c=T(a),l=m(c);!this.watchers.has(l)&&l!==e&&this.watchDirectory(l)}this.debounceRegeneration(a,f)});this.watchers.set(e,r),r.on("error",s=>{console.error(`❌ Watch error in ${e}:`,s)})}debounceRegeneration(t,e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(async()=>{if(!(!this.generatorOptions||!this.callback))try{const r=await S(this.generatorOptions),s=e;this.callback&&this.callback({type:s,file:t}),r.success?console.log(`✅ Regenerated translations (${r.translationsGenerated} translations from ${r.filesFound} file(s))`):console.error(`❌ Regeneration failed: ${r.errors.map(o=>o.message).join(", ")}`)}catch(r){const s=r instanceof Error?r.message:"Unknown error";console.error(`❌ Watch regeneration error: ${s}`)}},mt)}setGeneratorOptions(t){this.generatorOptions=t}stop(){if(this.isWatching){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null);for(const[,t]of this.watchers.entries())t.close();this.watchers.clear(),this.isWatching=!1,this.generatorOptions=null,this.callback=null}}}async function bt(n){const t=new $t;t.setGeneratorOptions(n),console.log("🔍 Watching for translation file changes...");const e=await S(n);e.success?console.log(`✅ Initial generation: ${e.translationsGenerated} translations from ${e.filesFound} file(s)`):console.error(`❌ Initial generation failed: ${e.errors.map(s=>s.message).join(", ")}`),await t.watch(n.pattern,()=>{});const r=()=>{console.log(`
34
+ 👋 Stopping watch mode...`),t.stop(),process.exit(0)};return process.on("SIGINT",r),process.on("SIGTERM",r),new Promise(()=>{})}var Tt={};const h={reset:"\x1B[0m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m"},j={searching:"🔍",success:"✅",error:"❌"};function vt(n){const t={};let e=0;for(;e<n.length;){const r=n[e];if(r.startsWith("--")&&r.includes("=")){const[s,...o]=r.slice(2).split("="),a=o.join("=");t[s]=a||!0,e++;continue}if(r.startsWith("--")){const s=r.slice(2);e+1<n.length&&!n[e+1].startsWith("--")?(t[s]=n[e+1],e+=2):(t[s]=!0,e++);continue}if(r.startsWith("-")&&!r.startsWith("--")){const s=r.slice(1);t[s]=!0,e++;continue}e++}return t}function Ft(){const n=`
35
+ ${h.blue}vbss-translator generate${h.reset}
36
36
  Generate translation index files from translation JSON files.
37
- ${g.yellow}Usage:${g.reset}
37
+ ${h.yellow}Usage:${h.reset}
38
38
  npx vbss-translator generate [options]
39
39
  npm run generate-translations [options]
40
- ${g.yellow}Options:${g.reset}
40
+ ${h.yellow}Options:${h.reset}
41
41
  --pattern <glob> Glob pattern to search for translation files
42
42
  (default: "src/**/translations.json")
43
43
  --output <path> Output file path
@@ -48,11 +48,11 @@ ${g.yellow}Options:${g.reset}
48
48
  (default: "vbss-translator.config.json")
49
49
  --reference-language <lang> Reference language for deduplication
50
50
  --help, -h Show this help message
51
- ${g.yellow}Examples:${g.reset}
51
+ ${h.yellow}Examples:${h.reset}
52
52
  npx vbss-translator generate
53
53
  npx vbss-translator generate --pattern "src/**/*.json" --output "src/translations.ts"
54
54
  npx vbss-translator generate --format js --reference-language en
55
- ${g.yellow}Configuration:${g.reset}
55
+ ${h.yellow}Configuration:${h.reset}
56
56
  Create a "vbss-translator.config.json" file in your project root:
57
57
  {
58
58
  "pattern": "src/**/translations.json",
@@ -61,4 +61,4 @@ ${g.yellow}Configuration:${g.reset}
61
61
  "referenceLanguage": "en"
62
62
  }
63
63
  CLI flags take precedence over config file settings.
64
- `;console.log(o)}function v(o){return`${g.red}${b.error} ${o}${g.reset}`}function X(o){return`${g.green}${b.success} ${o}${g.reset}`}function Y(o){return`${g.blue}${b.searching} ${o}${g.reset}`}async function Q(){const o=process.argv.slice(2),t=V(o);(t.help||t.h)&&(K(),process.exit(0));try{const e=typeof t.config=="string"?t.config:"vbss-translator.config.json",n=d(process.cwd(),e),s=await y.loadFromFile(n),a=y.loadFromArgs({pattern:t.pattern,output:t.output,format:t.format,"reference-language":t["reference-language"]}),r=y.merge(s||{},a);console.log(Y(`Searching for translation files matching: ${r.pattern}`));const u={pattern:r.pattern,outputPath:d(process.cwd(),r.outputPath),outputFormat:r.outputFormat,referenceLanguage:r.referenceLanguage,watch:t.watch===!0||t.w===!0};if(u.watch){await q(u);return}const l=Date.now(),i=await E(u),f=Date.now()-l;if(i.success)console.log(X(`Generated ${i.translationsGenerated} translations from ${i.filesFound} file(s)`)),console.log(`${g.green}Output:${g.reset} ${i.outputPath}`),console.log(`${g.green}Time:${g.reset} ${f}ms`),process.exit(0);else{console.error(v("Generation failed with errors:"));for(const c of i.errors)console.error(`${g.red} ${c.type}:${g.reset} ${c.file}`),console.error(` ${c.message}`);const h=i.errors.some(c=>c.type==="validation"||c.type==="missing_languages");process.exit(h?2:1)}}catch(e){const n=e instanceof Error?e.message:"Unknown error occurred";console.error(v(n)),e instanceof Error&&e.stack&&(console.error(`${g.red}Stack trace:${g.reset}`),console.error(e.stack)),process.exit(1)}}H.JEST_WORKER_ID||process.argv[1]&&(process.argv[1].includes("cli/index")||process.argv[1].includes("vbss-translator"))&&Q().catch(t=>{const e=t instanceof Error?t.message:"Unknown error occurred";console.error(v(`Fatal error: ${e}`)),process.exit(1)});
64
+ `;console.log(n)}function P(n){return`${h.red}${j.error} ${n}${h.reset}`}function Et(n){return`${h.green}${j.success} ${n}${h.reset}`}function Pt(n){return`${h.blue}${j.searching} ${n}${h.reset}`}async function Ot(){const n=process.argv.slice(2),t=vt(n);(t.help||t.h)&&(Ft(),process.exit(0));try{const e=typeof t.config=="string"?t.config:"vbss-translator.config.json",r=w(process.cwd(),e),s=await F.loadFromFile(r),o=F.loadFromArgs({pattern:t.pattern,output:t.output,format:t.format,"reference-language":t["reference-language"]}),a=F.merge(s||{},o);console.log(Pt(`Searching for translation files matching: ${a.pattern}`));const i={pattern:a.pattern,outputPath:w(process.cwd(),a.outputPath),outputFormat:a.outputFormat,referenceLanguage:a.referenceLanguage,watch:t.watch===!0||t.w===!0};if(i.watch){await bt(i);return}const f=Date.now(),c=await S(i),l=Date.now()-f;if(c.success)console.log(Et(`Generated ${c.translationsGenerated} translations from ${c.filesFound} file(s)`)),console.log(`${h.green}Output:${h.reset} ${c.outputPath}`),console.log(`${h.green}Time:${h.reset} ${l}ms`),process.exit(0);else{console.error(P("Generation failed with errors:"));for(const u of c.errors)console.error(`${h.red} ${u.type}:${h.reset} ${u.file}`),console.error(` ${u.message}`);const g=c.errors.some(u=>u.type==="validation"||u.type==="missing_languages");process.exit(g?2:1)}}catch(e){const r=e instanceof Error?e.message:"Unknown error occurred";console.error(P(r)),e instanceof Error&&e.stack&&!(e instanceof M)&&(console.error(`${h.red}Stack trace:${h.reset}`),console.error(e.stack)),process.exit(1)}}function St(n){if(!n)return!1;const t=n.split("\\").join("/");return t.includes("cli/index")||t.includes("vbss-translator")}Tt.JEST_WORKER_ID||St(process.argv[1])&&Ot().catch(n=>{const t=n instanceof Error?n.message:"Unknown error occurred";console.error(P(`Fatal error: ${t}`)),process.exit(1)});
@@ -1,32 +1,32 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("glob"),d=require("fs/promises"),h=require("path");async function v(n){try{const r=await y.glob(n,{cwd:process.cwd(),absolute:!1}),t=process.cwd();return r.map(e=>({path:h.resolve(t,e),relativePath:h.normalize(e).replace(/\\/g,"/"),translations:[]}))}catch(r){const t=r instanceof Error?r.message:"Unknown error";return[{path:"",relativePath:"",translations:[],error:{file:n,message:`Failed to discover files: ${t}`,type:"file_system"}}]}}async function $(n){const r=n.map(async t=>{if(t.error)return t;try{const e=await d.readFile(t.path,"utf-8"),a=JSON.parse(e),o=[];if(Array.isArray(a))for(const s of a){if(typeof s!="object"||s===null)return{...t,translations:[],error:{file:t.path,message:"Translation array must contain objects only",type:"validation"}};const c={};for(const[u,i]of Object.entries(s)){if(typeof i!="string")return{...t,translations:[],error:{file:t.path,message:`Translation value for key "${u}" must be a string, got ${typeof i}`,type:"validation"}};c[u]=i}o.push(c)}else if(typeof a=="object"&&a!==null){const s={};for(const[c,u]of Object.entries(a)){if(typeof u!="string")return{...t,translations:[],error:{file:t.path,message:`Translation value for key "${c}" must be a string, got ${typeof u}`,type:"validation"}};s[c]=u}return o.push(s),{...t,translations:o,wasSingleObject:!0}}else return{...t,translations:[],error:{file:t.path,message:"Translation file must contain a JSON object or array of objects",type:"validation"}};return{...t,translations:o}}catch(e){if(e instanceof SyntaxError)return{...t,translations:[],error:{file:t.path,message:`Invalid JSON: ${e.message}`,type:"invalid_json"}};const a=e instanceof Error?e.message:"Unknown error";return{...t,translations:[],error:{file:t.path,message:`Failed to read file: ${a}`,type:"file_system"}}}});return Promise.all(r)}function j(n){for(const r of n)if(!r.error&&r.translations.length>0)return Object.keys(r.translations[0]);return null}function P(n,r){const t=[];for(const e of n){if(e.error)continue;if(e.translations.length===0){t.push({file:e.path,message:"File has no translations",type:"validation"});continue}const a=Object.keys(e.translations[0]);for(let i=1;i<e.translations.length;i++){const f=Object.keys(e.translations[i]);if(JSON.stringify([...f].sort())!==JSON.stringify([...a].sort())){t.push({file:e.path,message:`Translation ${i+1} in file has different language keys`,type:"validation"});continue}}const o=[...a].sort(),s=[...r].sort(),c=s.filter(i=>!o.includes(i)),u=o.filter(i=>!s.includes(i));if(c.length>0||u.length>0){const i=[];c.length>0&&i.push(`missing languages: ${c.join(", ")}`),u.length>0&&i.push(`extra languages: ${u.join(", ")}`),t.push({file:e.path,message:`Language mismatch: ${i.join(", ")}. Expected: ${r.join(", ")}`,type:"missing_languages"})}}return t}function T(n,r){const t=new Set,e=[];for(const a of n){const o=a[r];if(o===void 0){e.push(a);continue}const s=o;t.has(s)||(t.add(s),e.push(a))}return e}function b(n,r){const t=h.dirname(n),e=r;let a=h.relative(t,e);return a=h.normalize(a).replace(/\\/g,"/"),a.startsWith(".")||(a="./"+a),a}function m(n,r,t){const e=n.filter(f=>!f.error&&f.translations.length>0).sort((f,g)=>f.path.localeCompare(g.path));if(e.length===0)return`export default []
2
- `;const a=e.map((f,g)=>{const l=b(r,f.path);return`import translations${g} from '${l}' assert { type: 'json' };`}).join(`
3
- `),o=e.map((f,g)=>f.wasSingleObject?` ...(Array.isArray(translations${g}) ? translations${g} : [translations${g}])`:` ...translations${g}`).join(`,
4
- `),c=`export interface Translation {
5
- ${t.map(f=>` ${f}: string;`).join(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("fs/promises"),p=require("path"),P=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"]),S=new Set(["win32","darwin"]),F=t=>typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"&&P.has(t.code),v=async t=>{try{return await m.readdir(t,{withFileTypes:!0})}catch(n){if(F(n))return[];throw n}},j=async t=>{try{return await m.stat(t)}catch(n){if(F(n))return null;throw n}},k=t=>t.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&"),E=t=>t.replace(/[\\\][^]/g,"\\$&"),O=(t,n)=>{const e=[];let s=0,a=n+1;for(let r=n;r<t.length;r++){const o=t[r];if(o==="{")s++;else if(o==="}"){if(s--,s===0)return e.push(t.slice(a,r)),{alternatives:e,end:r}}else o===","&&s===1&&(e.push(t.slice(a,r)),a=r+1)}return{alternatives:e,end:-1}},$=t=>{const n=t.indexOf("{");if(n===-1)return[t];const{alternatives:e,end:s}=O(t,n);if(s===-1)return[t];const a=t.slice(0,n),r=t.slice(s+1);if(e.length<2){const o=t.slice(n,s+1);return $(r).map(u=>a+o+u)}return e.flatMap(o=>$(a+o+r))},x=(t,n)=>{let e="";for(let s=0;s<t.length;s++){const a=t[s];if(a==="*")e+="[^/]*";else if(a==="?")e+="[^/]";else if(a==="["){const r=t.indexOf("]",s+2);if(r===-1)e+="\\[";else{const o=t.slice(s+1,r),u=o.startsWith("!")||o.startsWith("^");e+=`[${u?"^":""}${E(u?o.slice(1):o)}]`,s=r}}else e+=k(a)}return new RegExp(`^${e}$`,n?"i":"")},D=(t,n)=>{var s;const e=[];for(const a of t)a==="**"?((s=e[e.length-1])==null?void 0:s.kind)!=="globstar"&&e.push({kind:"globstar"}):/[*?[]/.test(a)?e.push({kind:"pattern",regexp:x(a,n),matchesDotfiles:a.startsWith(".")}):e.push({kind:"literal",text:a});return e},b=async(t,n)=>{var e;return n.isFile()?!0:n.isSymbolicLink()?((e=await j(p.join(t,n.name)))==null?void 0:e.isFile())??!1:!1},L=async(t,n)=>{var e;return n.isDirectory()?!0:n.isSymbolicLink()?((e=await j(p.join(t,n.name)))==null?void 0:e.isDirectory())??!1:!1};async function C(t,n){const e=S.has(process.platform),s=new Set;for(const a of $(t.replace(/\\/g,"/"))){const r=p.isAbsolute(a)?p.parse(a).root:"",o=a.slice(r.length).split("/").filter(i=>i!==""&&i!==".");if(o.length===0)continue;const u=D(o,e),f=(i,h,c)=>{s.add(r||n.absolute?p.resolve(i,c):[...h,c].join("/"))},l=async(i,h,c)=>{const d=u[c],y=c===u.length-1;if(d.kind==="globstar"){y||await l(i,h,c+1);for(const g of await v(i))g.name.startsWith(".")||(g.isDirectory()?await l(p.join(i,g.name),[...h,g.name],c):y&&await b(i,g)&&f(i,h,g.name));return}if(d.kind==="literal"){const g=p.join(i,d.text),w=await j(g);if(!w)return;y?w.isFile()&&f(i,h,d.text):w.isDirectory()&&await l(g,[...h,d.text],c+1);return}for(const g of await v(i))d.regexp.test(g.name)&&(g.name.startsWith(".")&&!d.matchesDotfiles||(y?await b(i,g)&&f(i,h,g.name):await L(i,g)&&await l(p.join(i,g.name),[...h,g.name],c+1)))};await l(r||p.resolve(n.cwd),[],0)}return[...s].sort()}async function N(t){try{const n=await C(t,{cwd:process.cwd(),absolute:!1}),e=process.cwd();return n.map(s=>({path:p.resolve(e,s),relativePath:p.normalize(s).replace(/\\/g,"/"),translations:[]}))}catch(n){const e=n instanceof Error?n.message:"Unknown error";return[{path:"",relativePath:"",translations:[],error:{file:t,message:`Failed to discover files: ${e}`,type:"file_system"}}]}}async function R(t){const n=t.map(async e=>{if(e.error)return e;try{const s=await m.readFile(e.path,"utf-8"),a=JSON.parse(s),r=[];if(Array.isArray(a))for(const o of a){if(typeof o!="object"||o===null)return{...e,translations:[],error:{file:e.path,message:"Translation array must contain objects only",type:"validation"}};const u={};for(const[f,l]of Object.entries(o)){if(typeof l!="string")return{...e,translations:[],error:{file:e.path,message:`Translation value for key "${f}" must be a string, got ${typeof l}`,type:"validation"}};u[f]=l}r.push(u)}else if(typeof a=="object"&&a!==null){const o={};for(const[u,f]of Object.entries(a)){if(typeof f!="string")return{...e,translations:[],error:{file:e.path,message:`Translation value for key "${u}" must be a string, got ${typeof f}`,type:"validation"}};o[u]=f}return r.push(o),{...e,translations:r,wasSingleObject:!0}}else return{...e,translations:[],error:{file:e.path,message:"Translation file must contain a JSON object or array of objects",type:"validation"}};return{...e,translations:r}}catch(s){if(s instanceof SyntaxError)return{...e,translations:[],error:{file:e.path,message:`Invalid JSON: ${s.message}`,type:"invalid_json"}};const a=s instanceof Error?s.message:"Unknown error";return{...e,translations:[],error:{file:e.path,message:`Failed to read file: ${a}`,type:"file_system"}}}});return Promise.all(n)}function A(t){for(const n of t)if(!n.error&&n.translations.length>0)return Object.keys(n.translations[0]);return null}function I(t,n){const e=[];for(const s of t){if(s.error)continue;if(s.translations.length===0){e.push({file:s.path,message:"File has no translations",type:"validation"});continue}const a=Object.keys(s.translations[0]);for(let l=1;l<s.translations.length;l++){const i=Object.keys(s.translations[l]);if(JSON.stringify([...i].sort())!==JSON.stringify([...a].sort())){e.push({file:s.path,message:`Translation ${l+1} in file has different language keys`,type:"validation"});continue}}const r=[...a].sort(),o=[...n].sort(),u=o.filter(l=>!r.includes(l)),f=r.filter(l=>!o.includes(l));if(u.length>0||f.length>0){const l=[];u.length>0&&l.push(`missing languages: ${u.join(", ")}`),f.length>0&&l.push(`extra languages: ${f.join(", ")}`),e.push({file:s.path,message:`Language mismatch: ${l.join(", ")}. Expected: ${n.join(", ")}`,type:"missing_languages"})}}return e}function G(t,n){const e=new Set,s=[];for(const a of t){const r=a[n];if(r===void 0){s.push(a);continue}const o=r;e.has(o)||(e.add(o),s.push(a))}return s}function _(t,n){const e=p.dirname(t),s=n;let a=p.relative(e,s);return a=p.normalize(a).replace(/\\/g,"/"),a.startsWith(".")||(a="./"+a),a}function T(t,n,e){const s=t.filter(i=>!i.error&&i.translations.length>0).sort((i,h)=>i.path.localeCompare(h.path));if(s.length===0)return`export default []
2
+ `;const a=s.map((i,h)=>{const c=_(n,i.path);return`import translations${h} from '${c}' assert { type: 'json' };`}).join(`
3
+ `),r=s.map((i,h)=>i.wasSingleObject?` ...(Array.isArray(translations${h}) ? translations${h} : [translations${h}])`:` ...translations${h}`).join(`,
4
+ `),u=`export interface Translation {
5
+ ${e.map(i=>` ${i}: string;`).join(`
6
6
  `)}
7
7
  [key: string]: string;
8
- }`,u=t[0]||"en",i=e.length>0?`
8
+ }`,f=e[0]||"en",l=s.length>0?`
9
9
  const uniqueTranslations = allTranslations.filter(
10
- (translation, index, self) => index === self.findIndex((t) => t.${u} === translation.${u})
10
+ (translation, index, self) => index === self.findIndex((t) => t.${f} === translation.${f})
11
11
  );`:"";return`${a}
12
12
 
13
- ${c}
13
+ ${u}
14
14
 
15
15
  const allTranslations: Translation[] = [
16
- ${o}
17
- ];${i}
16
+ ${r}
17
+ ];${l}
18
18
 
19
19
  export default uniqueTranslations;
20
- `}function F(n){const r=n.filter(s=>!s.error&&s.translations.length>0).sort((s,c)=>s.path.localeCompare(c.path));if(r.length===0)return`export default []
21
- `;const t=[];for(const s of r)s.wasSingleObject&&s.translations.length===1?t.push(s.translations[0]):t.push(...s.translations);const e=t.length>0?Object.keys(t[0])[0]:"en",a=t.map(s=>JSON.stringify(s,null,2).split(`
22
- `).map(i=>` ${i}`).join(`
20
+ `}function q(t){const n=t.filter(o=>!o.error&&o.translations.length>0).sort((o,u)=>o.path.localeCompare(u.path));if(n.length===0)return`export default []
21
+ `;const e=[];for(const o of n)o.wasSingleObject&&o.translations.length===1?e.push(o.translations[0]):e.push(...o.translations);const s=e.length>0?Object.keys(e[0])[0]:"en",a=e.map(o=>JSON.stringify(o,null,2).split(`
22
+ `).map(l=>` ${l}`).join(`
23
23
  `)).join(`,
24
- `),o=`
24
+ `),r=`
25
25
  const uniqueTranslations = allTranslations.filter(
26
- (translation, index, self) => index === self.findIndex((t) => t.${e} === translation.${e})
26
+ (translation, index, self) => index === self.findIndex((t) => t.${s} === translation.${s})
27
27
  );`;return`const allTranslations = [
28
28
  ${a}
29
- ];${o}
29
+ ];${r}
30
30
 
31
31
  export default uniqueTranslations;
32
- `}function w(n,r,t){return m(n,r,t)}async function k(n){const r=[],t=Date.now(),e=await v(n.pattern);if(e.length===0)return{success:!0,filesFound:0,translationsGenerated:0,errors:[],outputPath:n.outputPath};for(const l of e)l.error&&r.push(l.error);const a=await $(e);for(const l of a)l.error&&r.push(l.error);const o=j(a);if((!o||o.length===0)&&a.filter(p=>!p.error&&p.translations.length>0).length===0)return{success:!1,filesFound:e.length,translationsGenerated:0,errors:r.length>0?r:[{file:n.pattern,message:"No valid translation files found",type:"validation"}],outputPath:n.outputPath};if(o&&o.length>0){const l=P(a,o);if(r.push(...l),l.length>0)return{success:!1,filesFound:e.length,translationsGenerated:0,errors:r,outputPath:n.outputPath}}const s=[];for(const l of a)!l.error&&l.translations.length>0&&s.push(...l.translations);const c=n.referenceLanguage||(o==null?void 0:o[0])||"en",u=T(s,c);let i;const f=a.filter(l=>!l.error&&l.translations.length>0);switch(n.outputFormat){case"ts":i=m(f,n.outputPath,o||[]);break;case"tsx":i=w(f,n.outputPath,o||[]);break;case"js":i=F(f);break;default:return{success:!1,filesFound:e.length,translationsGenerated:0,errors:[...r,{file:n.outputPath,message:`Unsupported output format: ${n.outputFormat}`,type:"validation"}],outputPath:n.outputPath}}try{const l=h.dirname(n.outputPath);await d.mkdir(l,{recursive:!0}),await d.writeFile(n.outputPath,i,"utf-8")}catch(l){const p=l instanceof Error?l.message:"Unknown error";return r.push({file:n.outputPath,message:`Failed to write output file: ${p}`,type:"file_system"}),{success:!1,filesFound:e.length,translationsGenerated:u.length,errors:r,outputPath:n.outputPath}}const g=Date.now()-t;return g>1e3&&e.length<100&&console.warn(`⚠️ Generation took ${g}ms for ${e.length} files`),{success:r.length===0,filesFound:e.length,translationsGenerated:u.length,errors:r,outputPath:n.outputPath}}exports.generate=k;
32
+ `}function J(t,n,e){return T(t,n,e)}async function M(t){const n=[],e=Date.now(),s=await N(t.pattern);if(s.length===0)return{success:!0,filesFound:0,translationsGenerated:0,errors:[],outputPath:t.outputPath};const a=await R(s);for(const c of a)c.error&&n.push(c.error);const r=A(a);if((!r||r.length===0)&&a.filter(d=>!d.error&&d.translations.length>0).length===0)return{success:!1,filesFound:s.length,translationsGenerated:0,errors:n.length>0?n:[{file:t.pattern,message:"No valid translation files found",type:"validation"}],outputPath:t.outputPath};if(r&&r.length>0){const c=I(a,r);if(n.push(...c),c.length>0)return{success:!1,filesFound:s.length,translationsGenerated:0,errors:n,outputPath:t.outputPath}}const o=[];for(const c of a)!c.error&&c.translations.length>0&&o.push(...c.translations);const u=t.referenceLanguage||(r==null?void 0:r[0])||"en",f=G(o,u);let l;const i=a.filter(c=>!c.error&&c.translations.length>0);switch(t.outputFormat){case"ts":l=T(i,t.outputPath,r||[]);break;case"tsx":l=J(i,t.outputPath,r||[]);break;case"js":l=q(i);break;default:return{success:!1,filesFound:s.length,translationsGenerated:0,errors:[...n,{file:t.outputPath,message:`Unsupported output format: ${t.outputFormat}`,type:"validation"}],outputPath:t.outputPath}}try{const c=p.dirname(t.outputPath);await m.mkdir(c,{recursive:!0}),await m.writeFile(t.outputPath,l,"utf-8")}catch(c){const d=c instanceof Error?c.message:"Unknown error";return n.push({file:t.outputPath,message:`Failed to write output file: ${d}`,type:"file_system"}),{success:!1,filesFound:s.length,translationsGenerated:f.length,errors:n,outputPath:t.outputPath}}const h=Date.now()-e;return h>1e3&&s.length<100&&console.warn(`⚠️ Generation took ${h}ms for ${s.length} files`),{success:n.length===0,filesFound:s.length,translationsGenerated:f.length,errors:n,outputPath:t.outputPath}}exports.generate=M;