lexisync 0.2.1 → 1.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/README.md CHANGED
@@ -1,8 +1,11 @@
1
1
  # lexisync
2
2
 
3
- Official **CLI**, **i18next backend**, and HTTP client for [LexiSync](https://lexisync.app) — API-first, Locize-style translation management.
3
+ Official **CLI**, **i18next backend**, and HTTP client for [LexiSync](https://github.com/sanderpost/lexisync) — open-source, self-hosted, Locize-style translation management.
4
4
 
5
- [Docs](https://lexisync.app/docs) · [API discovery](https://lexisync.app/api/v1) · [OpenAPI](https://lexisync.app/api/v1/openapi.json)
5
+ [Self-hosting](https://github.com/sanderpost/lexisync/blob/main/docker/README.md) · API discovery: `{your-instance}/api/v1` · OpenAPI: `{your-instance}/api/v1/openapi.json`
6
+
7
+ > **1.0 breaking change:** there is no hosted default any more. Pass `apiUrl` (or set
8
+ > `LEXISYNC_API_URL` / `lexisync config api-url`) pointing at your own LexiSync instance.
6
9
 
7
10
  ## Install
8
11
 
@@ -16,41 +19,45 @@ npm install i18next
16
19
  npx lexisync --help
17
20
  ```
18
21
 
19
- Requires **Node.js ≥ 18**.
22
+ Requires **Node.js ≥ 20**.
20
23
 
21
24
  ## Quick start
22
25
 
23
- 1. Create an org + project at [lexisync.app](https://lexisync.app/onboarding/1)
26
+ 1. Run your own instance ([Docker guide](https://github.com/sanderpost/lexisync/blob/main/docker/README.md)) and create a project
24
27
  2. Copy **project id** and secret API key (`sk_…`)
25
28
  3. Sync source strings, translate, publish a version, load from CDN
26
29
 
27
30
  ```bash
28
- export LEXISYNC_API_KEY=sk_your_secret
31
+ npx lexisync config api-url https://lexisync.example.com
32
+ npx lexisync config api-key sk_your_secret
29
33
  npx lexisync sync -p YOUR_PROJECT_ID -f ./locales/en.json -l en
30
34
  npx lexisync publish -p YOUR_PROJECT_ID -v production
31
35
  npx lexisync pull -p YOUR_PROJECT_ID -n common -l en -v production -o ./locales/en.json
32
36
  ```
33
37
 
34
- Config is stored in `~/.lexisync/config.json`. Override API host with `LEXISYNC_API_URL` (default: `https://lexisync.app`). Override CDN with `LEXISYNC_CDN_URL` (default: `https://cdn.lexisync.app`).
38
+ Config is stored in `~/.lexisync/config.json`. The server URL comes from `LEXISYNC_API_URL` or `lexisync config api-url` (**required — no default**). The CDN defaults to `{apiUrl}/cdn`; override with `LEXISYNC_CDN_URL` if you serve catalogs from a dedicated host.
35
39
 
36
40
  ## Locize-style workflow
37
41
 
38
- | Step | What |
39
- |------|------|
40
- | 1. Keys | Dashboard → `projectId` + `sk_…` / `pub_…` |
42
+ | Step | What |
43
+ | --------------- | ----------------------------------------------------------------- |
44
+ | 1. Keys | Dashboard → `projectId` + `sk_…` / `pub_…` |
41
45
  | 2. Working copy | `lexisync sync` and/or `saveMissing: true` → version **`latest`** |
42
- | 3. Translate | Dashboard → project → Translate & publish |
43
- | 4. Publish | `lexisync publish -v production` freezes CDN catalogs |
44
- | 5. Ship | App loads `version: "production"` (live tag) or `latest` (dev) |
46
+ | 3. Translate | Dashboard → project → Translate & publish |
47
+ | 4. Publish | `lexisync publish -v production` → PublicationManifest + CDN tag |
48
+ | 5. Ship | App loads `version: "production"` (live tag) or `latest` (dev) |
49
+ | 6. Rollback | Dashboard **Releases** → Restore to CDN (working copy untouched) |
50
+
51
+ See the in-app docs on your instance (`/docs`).
45
52
 
46
53
  **CDN (no auth):**
47
54
 
48
55
  ```
49
- GET https://cdn.lexisync.app/{projectId}/{version}/{lng}/{namespace}.json
50
- GET https://cdn.lexisync.app/{projectId}/{version}/languages
56
+ GET {apiUrl}/cdn/{projectId}/{version}/{lng}/{namespace}
57
+ GET {apiUrl}/cdn/{projectId}/{version}/languages
51
58
  ```
52
59
 
53
- Also: `https://lexisync.app/cdn/{projectId}/{version}/{lng}/{namespace}`
60
+ With a dedicated CDN host (`cdnUrl`): `{cdnUrl}/{projectId}/{version}/{lng}/{namespace}.json`
54
61
 
55
62
  ## CLI
56
63
 
@@ -77,8 +84,8 @@ await i18next.use(LexiSyncBackend).init({
77
84
  backend: {
78
85
  projectId: 'YOUR_PROJECT_ID',
79
86
  apiKey: process.env.LEXISYNC_API_KEY, // needed for saveMissing
80
- apiUrl: 'https://lexisync.app', // optional — this is the default
81
- // cdnUrl: 'https://cdn.lexisync.app', // optional — auto when apiUrl is lexisync.app
87
+ apiUrl: 'https://lexisync.example.com', // required — your LexiSync instance
88
+ // cdnUrl: 'https://cdn.lexisync.example.com', // optional — default `${apiUrl}/cdn`
82
89
  version: 'latest', // use "production" after publish
83
90
  },
84
91
  saveMissing: true, // only writes when version === "latest"
@@ -109,7 +116,7 @@ const {
109
116
  cdnUrl,
110
117
  } = require('lexisync/client');
111
118
 
112
- const apiUrl = 'https://lexisync.app';
119
+ const apiUrl = 'https://lexisync.example.com'; // your instance
113
120
  const apiKey = process.env.LEXISYNC_API_KEY;
114
121
 
115
122
  await discoverApi({ apiUrl });
@@ -124,8 +131,8 @@ await downloadCatalog({
124
131
  });
125
132
 
126
133
  // Build a public CDN URL
127
- cdnUrl({ projectId: '…', version: 'production', language: 'en', namespace: 'common' });
128
- // → https://cdn.lexisync.app/…/production/en/common.json
134
+ cdnUrl({ apiUrl, projectId: '…', version: 'production', language: 'en', namespace: 'common' });
135
+ // → https://lexisync.example.com/cdn/…/production/en/common
129
136
  ```
130
137
 
131
138
  ## License
package/bin/lexisync.js CHANGED
@@ -18,13 +18,20 @@ const config = createConfig();
18
18
  const program = new Command();
19
19
 
20
20
  function apiBase() {
21
- return resolveApiUrl(process.env.LEXISYNC_API_URL || config.get('apiUrl'));
21
+ const url = process.env.LEXISYNC_API_URL || config.get('apiUrl');
22
+ if (!url) {
23
+ throw new Error(
24
+ 'No LexiSync server configured. Run `lexisync config api-url https://your-instance` ' +
25
+ 'or set LEXISYNC_API_URL.',
26
+ );
27
+ }
28
+ return resolveApiUrl(url);
22
29
  }
23
30
 
24
31
  program
25
32
  .name('lexisync')
26
33
  .description('LexiSync CLI — sync, pull, publish versioned catalogs (Locize-style)')
27
- .version('0.2.0');
34
+ .version(require('../package.json').version);
28
35
 
29
36
  program
30
37
  .command('init')
@@ -65,7 +72,9 @@ program
65
72
  const apiKey = config.get('apiKey');
66
73
  const projectId = options.project || config.get('projectId');
67
74
  if (!apiKey) {
68
- console.error('Error: Not authenticated. Run lexisync init or set apiKey in ~/.lexisync/config.json');
75
+ console.error(
76
+ 'Error: Not authenticated. Run lexisync init or set apiKey in ~/.lexisync/config.json',
77
+ );
69
78
  process.exitCode = 1;
70
79
  return;
71
80
  }
@@ -83,7 +92,7 @@ program
83
92
  const response = await axios.post(
84
93
  `${apiBase()}/api/sync`,
85
94
  { projectId, languageCode: options.lang, data },
86
- { headers: { 'x-api-key': apiKey } }
95
+ { headers: { 'x-api-key': apiKey } },
87
96
  );
88
97
 
89
98
  console.log('Sync complete:', response.data);
@@ -119,9 +128,7 @@ program
119
128
  const outPath = path.resolve(options.out);
120
129
  fs.mkdirSync(path.dirname(outPath), { recursive: true });
121
130
  fs.writeFileSync(outPath, JSON.stringify(resource, null, 2) + '\n');
122
- console.log(
123
- `Wrote ${Object.keys(resource).length} keys → ${outPath} (v=${options.version})`
124
- );
131
+ console.log(`Wrote ${Object.keys(resource).length} keys → ${outPath} (v=${options.version})`);
125
132
  console.log(
126
133
  'CDN URL:',
127
134
  cdnUrl({
@@ -130,7 +137,7 @@ program
130
137
  version: options.version,
131
138
  language: options.lang,
132
139
  namespace: options.namespace,
133
- })
140
+ }),
134
141
  );
135
142
  } catch (err) {
136
143
  console.error(`Error: ${err.message}`);
@@ -185,4 +192,385 @@ program
185
192
  }
186
193
  });
187
194
 
188
- program.parse(process.argv);
195
+ program
196
+ .command('config')
197
+ .description('Manage local CLI configuration (~/.lexisync/config.json)')
198
+ .argument('<key>', 'Configuration key (e.g. reference-language)')
199
+ .argument('[value]', 'Value to set; omit to read')
200
+ .action((key, value) => {
201
+ // Normalize kebab aliases → camelCase storage keys.
202
+ const map = {
203
+ 'reference-language': 'referenceLanguage',
204
+ 'source-language': 'referenceLanguage', // deprecated alias
205
+ 'project-id': 'projectId',
206
+ 'api-key': 'apiKey',
207
+ 'api-url': 'apiUrl',
208
+ };
209
+ const storeKey = map[key] || key;
210
+ if (value === undefined) {
211
+ const cur = config.get(storeKey);
212
+ if (cur === undefined || cur === null) {
213
+ console.log(`${key} (unset)`);
214
+ } else {
215
+ console.log(`${key} = ${cur}`);
216
+ }
217
+ } else {
218
+ config.set(storeKey, value);
219
+ // Keep deprecated sourceLanguage mirrored when setting reference.
220
+ if (storeKey === 'referenceLanguage') {
221
+ config.set('sourceLanguage', value);
222
+ }
223
+ console.log(`${key} = ${value}`);
224
+ }
225
+ });
226
+
227
+ program
228
+ .command('project')
229
+ .description('Create a new project under the current organization')
230
+ .option('-n, --name <name>', 'Project name (required)', '')
231
+ .option(
232
+ '-r, --reference-language <lng>',
233
+ 'Reference language (Locize-style; where defaultValues / saveMissing land)',
234
+ 'en',
235
+ )
236
+ .option('-s, --source-language <lng>', 'Deprecated alias of --reference-language', '')
237
+ .option('-l, --languages <codes>', 'Comma-separated extra languages to enable')
238
+ .action(async (options) => {
239
+ const apiKey = config.get('apiKey');
240
+ if (!apiKey) {
241
+ console.error("Error: Not authenticated. Run 'lexisync init' first.");
242
+ process.exitCode = 1;
243
+ return;
244
+ }
245
+ if (!options.name.trim()) {
246
+ console.error('Error: --name <name> is required.');
247
+ process.exitCode = 1;
248
+ return;
249
+ }
250
+ const isRealLang = (c) => /^[a-z]{2,3}(-[a-zA-Z0-9]{2,8})?$/i.test(String(c || '').trim());
251
+ const refRaw = options.referenceLanguage || options.sourceLanguage || 'en';
252
+ if (!isRealLang(refRaw)) {
253
+ console.error('Error: --reference-language must be a valid BCP-47 tag (e.g. en, nl, en-US).');
254
+ process.exitCode = 1;
255
+ return;
256
+ }
257
+ const referenceLng = String(refRaw).toLowerCase();
258
+ const extraLangs = (options.languages || '')
259
+ .split(',')
260
+ .map((s) => s.trim().toLowerCase())
261
+ .filter(Boolean);
262
+
263
+ try {
264
+ const body = {
265
+ name: options.name.trim(),
266
+ referenceLng,
267
+ languages: extraLangs,
268
+ };
269
+ const response = await axios.post(`${apiBase()}/api/v1/projects`, body, {
270
+ headers: { 'x-api-key': apiKey },
271
+ });
272
+ const p = response.data?.data || response.data;
273
+ console.log('Project created:');
274
+ console.log(` id ${p.id}`);
275
+ console.log(` name ${p.name}`);
276
+ console.log(` referenceLng ${p.referenceLng}`);
277
+ console.log(` languages ${(p.languages || []).join(', ')}`);
278
+ console.log('');
279
+ console.log('Now: lexisync config set reference-language ' + p.referenceLng);
280
+ console.log(' lexisync config set project-id ' + p.id);
281
+ config.set('referenceLanguage', p.referenceLng);
282
+ // Keep deprecated key mirrored for older scripts.
283
+ config.set('sourceLanguage', p.referenceLng);
284
+ config.set('projectId', p.id);
285
+ } catch (err) {
286
+ console.error('Error:', err.response?.data?.error || err.message);
287
+ process.exitCode = 1;
288
+ }
289
+ });
290
+
291
+ // ─── Phase 2: quality gates ───────────────────────────────────────────
292
+
293
+ function projectIdOrDie() {
294
+ const id = config.get('projectId');
295
+ if (!id) {
296
+ console.error('Error: projectId not set. Run: lexisync config set project-id <id>');
297
+ process.exit(1);
298
+ }
299
+ return id;
300
+ }
301
+
302
+ function authHeaders() {
303
+ const apiKey = config.get('apiKey');
304
+ if (!apiKey) {
305
+ console.error("Error: Not authenticated. Run 'lexisync init' first.");
306
+ process.exit(1);
307
+ }
308
+ return { 'x-api-key': apiKey, 'Content-Type': 'application/json' };
309
+ }
310
+
311
+ program
312
+ .command('check')
313
+ .description('Run localization quality checks (CI-friendly; exit 1 if not ready)')
314
+ .option('-e, --environment <env>', 'Environment label (preview|production)', 'preview')
315
+ .option('-l, --language <codes>', 'Comma-separated languages to check')
316
+ .option('--json', 'Print full JSON report')
317
+ .action(async (options) => {
318
+ const projectId = projectIdOrDie();
319
+ const languages = options.language
320
+ ? options.language
321
+ .split(',')
322
+ .map((s) => s.trim())
323
+ .filter(Boolean)
324
+ : undefined;
325
+ try {
326
+ const version = options.environment === 'production' ? 'production' : undefined;
327
+ const res = await axios.post(
328
+ `${apiBase()}/api/v1/projects/${projectId}/check`,
329
+ { languages, version, persist: true },
330
+ { headers: authHeaders() },
331
+ );
332
+ const data = res.data?.data || res.data;
333
+ if (options.json) {
334
+ console.log(JSON.stringify(data, null, 2));
335
+ } else {
336
+ console.log(`ready: ${data.ready ? 'yes' : 'NO'}`);
337
+ console.log(`checked: ${data.checked}`);
338
+ console.log(`blocking: ${data.blockingCount}`);
339
+ if (data.byCode) {
340
+ console.log('by code:');
341
+ for (const [k, v] of Object.entries(data.byCode)) {
342
+ console.log(` ${k}: ${v}`);
343
+ }
344
+ }
345
+ if (data.blocking?.length) {
346
+ console.log('top blockers:');
347
+ for (const b of data.blocking.slice(0, 15)) {
348
+ console.log(
349
+ ` [${b.severity}] ${b.code} ${b.namespace}/${b.identifier} @${b.languageCode}: ${b.message}`,
350
+ );
351
+ }
352
+ }
353
+ }
354
+ if (!data.ready) process.exitCode = 1;
355
+ } catch (err) {
356
+ console.error('Error:', err.response?.data?.error || err.message);
357
+ process.exitCode = 1;
358
+ }
359
+ });
360
+
361
+ program
362
+ .command('status')
363
+ .description('Readiness summary per language')
364
+ .option('-l, --language <code>', 'Single language')
365
+ .option('--json', 'Print JSON')
366
+ .action(async (options) => {
367
+ const projectId = projectIdOrDie();
368
+ try {
369
+ const q = options.language ? `?language=${encodeURIComponent(options.language)}` : '';
370
+ const res = await axios.get(`${apiBase()}/api/v1/projects/${projectId}/status${q}`, {
371
+ headers: authHeaders(),
372
+ });
373
+ const data = res.data?.data || res.data;
374
+ if (options.json) {
375
+ console.log(JSON.stringify(data, null, 2));
376
+ return;
377
+ }
378
+ if (data.language) {
379
+ const l = data.language;
380
+ console.log(
381
+ `${l.language}${l.isReference ? ' (reference)' : ''}: ready=${l.ready} filled=${l.filled}/${l.keys} empty=${l.empty} stale=${l.stale} errors=${l.errors} unapproved=${l.unapproved}`,
382
+ );
383
+ if (!l.ready) process.exitCode = 1;
384
+ return;
385
+ }
386
+ console.log(`reference: ${data.referenceLng} overall ready: ${data.ready ? 'yes' : 'NO'}`);
387
+ for (const l of data.languages || []) {
388
+ const mark = l.ready ? '✓' : '✗';
389
+ console.log(
390
+ ` ${mark} ${l.language.padEnd(8)} filled ${String(l.filled).padStart(4)}/${l.keys} empty ${l.empty} stale ${l.stale} err ${l.errors} unapproved ${l.unapproved}`,
391
+ );
392
+ }
393
+ if (!data.ready) process.exitCode = 1;
394
+ } catch (err) {
395
+ console.error('Error:', err.response?.data?.error || err.message);
396
+ process.exitCode = 1;
397
+ }
398
+ });
399
+
400
+ program
401
+ .command('diff')
402
+ .description('Working copy changes since a published version')
403
+ .option('--since <version>', 'Published version tag', 'production')
404
+ .option('--json', 'Print JSON')
405
+ .action(async (options) => {
406
+ const projectId = projectIdOrDie();
407
+ try {
408
+ const res = await axios.get(
409
+ `${apiBase()}/api/v1/projects/${projectId}/diff?since=${encodeURIComponent(options.since)}`,
410
+ { headers: authHeaders() },
411
+ );
412
+ const data = res.data?.data || res.data;
413
+ if (options.json) {
414
+ console.log(JSON.stringify(data, null, 2));
415
+ return;
416
+ }
417
+ console.log(
418
+ `since ${data.version}: +${data.counts.added} ~${data.counts.changed} -${data.counts.removed}`,
419
+ );
420
+ for (const c of (data.changed || []).slice(0, 30)) {
421
+ console.log(` ~ ${c.namespace}/${c.identifier} @${c.languageCode}`);
422
+ }
423
+ for (const a of (data.added || []).slice(0, 20)) {
424
+ console.log(` + ${a.namespace}/${a.identifier} @${a.languageCode}`);
425
+ }
426
+ for (const r of (data.removed || []).slice(0, 20)) {
427
+ console.log(` - ${r.namespace}/${r.identifier} @${r.languageCode}`);
428
+ }
429
+ } catch (err) {
430
+ console.error('Error:', err.response?.data?.error || err.message);
431
+ process.exitCode = 1;
432
+ }
433
+ });
434
+
435
+ program
436
+ .command('review')
437
+ .description('Review-lite: approve|reject|reopen a translation')
438
+ .argument('<action>', 'approve|reject|reopen')
439
+ .requiredOption('--key <identifier>', 'Key identifier')
440
+ .requiredOption('--lang <code>', 'Language code')
441
+ .option('--namespace <ns>', 'Namespace', 'common')
442
+ .action(async (action, options) => {
443
+ const projectId = projectIdOrDie();
444
+ if (!['approve', 'reject', 'reopen'].includes(action)) {
445
+ console.error('action must be approve|reject|reopen');
446
+ process.exitCode = 1;
447
+ return;
448
+ }
449
+ try {
450
+ const res = await axios.post(
451
+ `${apiBase()}/api/v1/projects/${projectId}/review`,
452
+ {
453
+ action,
454
+ identifier: options.key,
455
+ namespace: options.namespace,
456
+ languageCode: options.lang,
457
+ },
458
+ { headers: authHeaders() },
459
+ );
460
+ console.log(JSON.stringify(res.data?.data || res.data, null, 2));
461
+ } catch (err) {
462
+ console.error('Error:', err.response?.data?.error || err.message);
463
+ process.exitCode = 1;
464
+ }
465
+ });
466
+
467
+ // ─── CLI OAuth auth ────────────────────────────────────────────────────────
468
+
469
+ const crypto = require('crypto');
470
+ const http = require('http');
471
+ const { exec } = require('child_process');
472
+
473
+ function openBrowser(target) {
474
+ const cmd =
475
+ process.platform === 'darwin'
476
+ ? `open ${JSON.stringify(target)}`
477
+ : process.platform === 'win32'
478
+ ? `start "" ${JSON.stringify(target)}`
479
+ : `xdg-open ${JSON.stringify(target)}`;
480
+ exec(cmd);
481
+ }
482
+
483
+ function base64Url(buf) {
484
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
485
+ }
486
+
487
+ program
488
+ .command('auth')
489
+ .description('Authenticate the CLI via browser OAuth (stores API key in config)')
490
+ .argument('<url>', 'LexiSync base URL (e.g. http://localhost:3000)')
491
+ .action(async (url) => {
492
+ try {
493
+ const base = String(url).replace(/\/$/, '');
494
+ config.set('apiUrl', base);
495
+
496
+ const verifier = base64Url(crypto.randomBytes(32));
497
+ const challenge = base64Url(crypto.createHash('sha256').update(verifier).digest());
498
+ const state = base64Url(crypto.randomBytes(16));
499
+
500
+ const port = 8765;
501
+ const redirectUri = `http://localhost:${port}/callback`;
502
+
503
+ const code = await new Promise((resolve, reject) => {
504
+ const server = http.createServer((req, res) => {
505
+ const u = new URL(req.url, `http://localhost:${port}`);
506
+ if (u.pathname !== '/callback') {
507
+ res.statusCode = 404;
508
+ res.end('Not found');
509
+ return;
510
+ }
511
+ const err = u.searchParams.get('error');
512
+ const c = u.searchParams.get('code');
513
+ const st = u.searchParams.get('state');
514
+ if (err) {
515
+ res.end(`Auth error: ${err}`);
516
+ server.close();
517
+ reject(new Error(err));
518
+ return;
519
+ }
520
+ if (!c || st !== state) {
521
+ res.statusCode = 400;
522
+ res.end('Invalid callback');
523
+ return;
524
+ }
525
+ res.end('Authentication successful. You can close this window.');
526
+ server.close();
527
+ resolve(c);
528
+ });
529
+ server.listen(port, () => {
530
+ const authUrl = `${base}/api/cli/authorize?redirect_uri=${encodeURIComponent(
531
+ redirectUri,
532
+ )}&state=${encodeURIComponent(state)}&code_challenge=${encodeURIComponent(
533
+ challenge,
534
+ )}&code_challenge_method=S256`;
535
+ console.log('Opening browser for authentication...');
536
+ console.log(authUrl);
537
+ openBrowser(authUrl);
538
+ });
539
+ setTimeout(
540
+ () => {
541
+ server.close();
542
+ reject(new Error('Timed out waiting for auth callback'));
543
+ },
544
+ 5 * 60 * 1000,
545
+ );
546
+ });
547
+
548
+ const tokenRes = await axios.post(`${base}/api/cli/token`, {
549
+ code,
550
+ code_verifier: verifier,
551
+ redirect_uri: redirectUri,
552
+ });
553
+ const token = tokenRes.data.token;
554
+ if (!token) throw new Error('No token returned');
555
+ config.set('apiKey', token);
556
+ console.log('Authenticated. API key stored in config.');
557
+ } catch (err) {
558
+ console.error(`Error: ${err.response?.data?.error || err.message}`);
559
+ process.exitCode = 1;
560
+ }
561
+ });
562
+
563
+ program
564
+ .command('auth-token')
565
+ .description('Print the stored API token (like gh auth token)')
566
+ .action(() => {
567
+ const token = config.get('apiKey');
568
+ if (!token) {
569
+ console.error('Error: Not authenticated. Run lexisync auth <url>.');
570
+ process.exitCode = 1;
571
+ return;
572
+ }
573
+ console.log(token);
574
+ });
575
+
576
+ program.parse(process.argv);
package/lib/backend.js CHANGED
@@ -9,14 +9,19 @@ const { getTranslations, resolveApiUrl, upsertTranslation } = require('./client'
9
9
  * - version "latest" (default): working copy — good for development + saveMissing
10
10
  * - version "production" | "1.0.0" | …: published CDN catalog (immutable, cacheable)
11
11
  *
12
+ * Reference language (Locize term):
13
+ * backend.referenceLng — where saveMissing pushes defaultValues.
14
+ * Must match Project.referenceLng on the platform.
15
+ * Deprecated alias: backend.sourceLng (same meaning).
16
+ *
12
17
  * @example
13
18
  * import LexiSyncBackend from 'lexisync';
14
19
  * i18next.use(LexiSyncBackend).init({
15
20
  * backend: {
16
21
  * projectId: '…',
17
- * apiKey: 'sk_…', // write / saveMissing
18
- * version: 'latest', // or 'production'
19
- * apiUrl: 'https://…',
22
+ * apiKey: 'sk_…',
23
+ * version: 'production',
24
+ * referenceLng: 'nl',
20
25
  * },
21
26
  * saveMissing: true,
22
27
  * });
@@ -24,22 +29,36 @@ const { getTranslations, resolveApiUrl, upsertTranslation } = require('./client'
24
29
  class LexiSyncBackend {
25
30
  constructor(services, backendOptions = {}, i18nextOptions = {}) {
26
31
  this.services = services;
27
- this.options = {
32
+ this.options = this.#normalizeOptions(backendOptions);
33
+ this.i18nextOptions = i18nextOptions;
34
+ this.type = 'backend';
35
+ }
36
+
37
+ #normalizeOptions(backendOptions = {}) {
38
+ const referenceLng =
39
+ backendOptions.referenceLng ||
40
+ backendOptions.sourceLng || // deprecated alias
41
+ backendOptions.lng ||
42
+ 'en';
43
+ return {
28
44
  apiUrl: backendOptions.apiUrl,
29
45
  cdnUrl: backendOptions.cdnUrl,
30
46
  projectId: backendOptions.projectId,
31
47
  apiKey: backendOptions.apiKey,
32
48
  version: backendOptions.version || 'latest',
33
- referenceLng: backendOptions.referenceLng || backendOptions.lng,
49
+ referenceLng,
50
+ // Keep sourceLng as a mirrored deprecated property for older call sites.
51
+ sourceLng: referenceLng,
34
52
  ...backendOptions,
53
+ // Re-assert after spread so aliases cannot drift.
54
+ referenceLng,
55
+ sourceLng: referenceLng,
35
56
  };
36
- this.i18nextOptions = i18nextOptions;
37
- this.type = 'backend';
38
57
  }
39
58
 
40
59
  init(services, backendOptions = {}, i18nextOptions = {}) {
41
60
  this.services = services;
42
- this.options = { ...this.options, ...backendOptions };
61
+ this.options = this.#normalizeOptions({ ...this.options, ...backendOptions });
43
62
  if (!this.options.version) this.options.version = 'latest';
44
63
  this.i18nextOptions = i18nextOptions;
45
64
  }
@@ -63,15 +82,14 @@ class LexiSyncBackend {
63
82
  .catch((err) => callback(err, null));
64
83
  }
65
84
 
66
- /** i18next saveMissing → register new keys on the working copy (requires apiKey). */
85
+ /** i18next saveMissing → working copy in the project reference language. */
67
86
  create(languages, namespace, key, fallbackValue) {
68
- const { projectId, apiKey, apiUrl, referenceLng, version } = this.options;
87
+ const { projectId, apiKey, apiUrl, referenceLng } = this.options;
69
88
  if (!apiKey || !projectId) return;
70
- // Never write into a published version via CDN path — always latest working copy
71
- if (version && version !== 'latest') return;
72
89
 
73
90
  const lng = Array.isArray(languages) ? languages[0] : languages;
74
- const languageCode = lng || referenceLng || 'en';
91
+ // Prefer explicit language from i18next when provided; otherwise referenceLng.
92
+ const languageCode = lng || referenceLng;
75
93
  const value = typeof fallbackValue === 'string' ? fallbackValue : String(fallbackValue ?? key);
76
94
 
77
95
  upsertTranslation({
@@ -93,4 +111,4 @@ class LexiSyncBackend {
93
111
  LexiSyncBackend.type = 'backend';
94
112
 
95
113
  module.exports = LexiSyncBackend;
96
- module.exports.default = LexiSyncBackend;
114
+ module.exports.default = LexiSyncBackend;