@adminforth/i18n 1.0.18-next.5 → 1.0.18-next.7

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.
Files changed (3) hide show
  1. package/dist/index.js +79 -72
  2. package/index.ts +120 -101
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -13,6 +13,9 @@ import path from 'path';
13
13
  import fs from 'fs-extra';
14
14
  import chokidar from 'chokidar';
15
15
  import { AsyncQueue } from '@sapphire/async-queue';
16
+ console.log = (...args) => {
17
+ process.stdout.write(args.join(" ") + "\n");
18
+ };
16
19
  const processFrontendMessagesQueue = new AsyncQueue();
17
20
  const SLAVIC_PLURAL_EXAMPLES = {
18
21
  uk: 'яблук | Яблуко | Яблука | Яблук', // zero | singular | 2-4 | 5+
@@ -288,7 +291,7 @@ export default class I18N extends AdminForthPlugin {
288
291
  return { ok: false, error: e.message };
289
292
  }
290
293
  }
291
- process.env.HEAVY_DEBUG && console.log('🪲bulkTranslate done', selectedIds);
294
+ process.env.HEAVY_DEBUG && console.log('🪲bulkTranslate done', translatedCount);
292
295
  this.updateUntranslatedMenuBadge();
293
296
  return {
294
297
  ok: true,
@@ -325,6 +328,77 @@ export default class I18N extends AdminForthPlugin {
325
328
  });
326
329
  });
327
330
  }
331
+ translateToLang(langIsoCode_1, strings_1) {
332
+ return __awaiter(this, arguments, void 0, function* (langIsoCode, strings, plurals = false, translations, updateStrings = {}) {
333
+ const maxKeysInOneReq = 10;
334
+ if (strings.length === 0) {
335
+ return [];
336
+ }
337
+ if (strings.length > maxKeysInOneReq) {
338
+ let totalTranslated = [];
339
+ for (let i = 0; i < strings.length; i += maxKeysInOneReq) {
340
+ const slicedStrings = strings.slice(i, i + maxKeysInOneReq);
341
+ process.env.HEAVY_DEBUG && console.log('🪲🔪slicedStrings len', slicedStrings.length);
342
+ const madeKeys = yield this.translateToLang(langIsoCode, slicedStrings, plurals, translations, updateStrings);
343
+ totalTranslated = totalTranslated.concat(madeKeys);
344
+ }
345
+ return totalTranslated;
346
+ }
347
+ const lang = langIsoCode;
348
+ const requestSlavicPlurals = Object.keys(SLAVIC_PLURAL_EXAMPLES).includes(lang) && plurals;
349
+ const prompt = `
350
+ I need to translate strings in JSON to ${lang} language from English for my web app.
351
+ ${requestSlavicPlurals ? `You should provide 4 translations (in format zero | singular | 2-4 | 5+) e.g. ${SLAVIC_PLURAL_EXAMPLES[lang]}` : ''}
352
+ Keep keys, as is, write translation into values! Here are the strings:
353
+
354
+ \`\`\`json
355
+ ${JSON.stringify(strings.reduce((acc, s) => {
356
+ acc[s.en_string] = '';
357
+ return acc;
358
+ }, {}), null, 2)}
359
+ \`\`\`
360
+ `;
361
+ // process.env.HEAVY_DEBUG && console.log('🧠 llm prompt', prompt);
362
+ // call OpenAI
363
+ const resp = yield this.options.completeAdapter.complete(prompt, [], 300);
364
+ // process.env.HEAVY_DEBUG && console.log('🧠 llm resp', resp);
365
+ if (resp.error) {
366
+ throw new AiTranslateError(resp.error);
367
+ }
368
+ // parse response like
369
+ // Here are the translations for the strings you provided:
370
+ // ```json
371
+ // [{"live": "canlı"}, {"Table Games": "Masa Oyunları"}]
372
+ // ```
373
+ let res;
374
+ try {
375
+ res = resp.content.split("```json")[1].split("```")[0];
376
+ }
377
+ catch (e) {
378
+ console.error('error in parsing OpenAI', resp);
379
+ throw new AiTranslateError('Error in parsing OpenAI response');
380
+ }
381
+ res = JSON.parse(res);
382
+ for (const [enStr, translatedStr] of Object.entries(res)) {
383
+ const translationsTargeted = translations.filter(t => t[this.enFieldName] === enStr);
384
+ // might be several with same en_string
385
+ for (const translation of translationsTargeted) {
386
+ //translation[this.trFieldNames[lang]] = translatedStr;
387
+ // process.env.HEAVY_DEBUG && console.log(`🪲translated to ${lang} ${translation.en_string}, ${translatedStr}`)
388
+ if (!updateStrings[translation[this.primaryKeyFieldName]]) {
389
+ updateStrings[translation[this.primaryKeyFieldName]] = {
390
+ updates: {},
391
+ translatedStr,
392
+ category: translation[this.options.categoryFieldName],
393
+ strId: translation[this.primaryKeyFieldName],
394
+ };
395
+ }
396
+ updateStrings[translation[this.primaryKeyFieldName]].updates[this.trFieldNames[lang]] = translatedStr;
397
+ }
398
+ }
399
+ return Object.keys(updateStrings);
400
+ });
401
+ }
328
402
  // returns translated count
329
403
  bulkTranslate(_a) {
330
404
  return __awaiter(this, arguments, void 0, function* ({ selectedIds }) {
@@ -349,89 +423,22 @@ export default class I18N extends AdminForthPlugin {
349
423
  }
350
424
  const maxKeysInOneReq = 10;
351
425
  const updateStrings = {};
352
- const translateToLang = (langIsoCode_1, strings_1, ...args_1) => __awaiter(this, [langIsoCode_1, strings_1, ...args_1], void 0, function* (langIsoCode, strings, plurals = false) {
353
- if (strings.length === 0) {
354
- return [];
355
- }
356
- if (strings.length > maxKeysInOneReq) {
357
- let totalTranslated = [];
358
- for (let i = 0; i < strings.length; i += maxKeysInOneReq) {
359
- const slicedStrings = strings.slice(i, i + maxKeysInOneReq);
360
- process.env.HEAVY_DEBUG && console.log('🪲🔪slicedStrings len', slicedStrings.length);
361
- const madeKeys = yield translateToLang(langIsoCode, slicedStrings, plurals);
362
- totalTranslated = totalTranslated.concat(madeKeys);
363
- }
364
- return totalTranslated;
365
- }
366
- const lang = langIsoCode;
367
- const requestSlavicPlurals = Object.keys(SLAVIC_PLURAL_EXAMPLES).includes(lang) && plurals;
368
- const prompt = `
369
- I need to translate strings in JSON to ${lang} language from English for my web app.
370
- ${requestSlavicPlurals ? `You should provide 4 translations (in format zero | singular | 2-4 | 5+) e.g. ${SLAVIC_PLURAL_EXAMPLES[lang]}` : ''}
371
- Keep keys, as is, write translation into values! Here are the strings:
372
-
373
- \`\`\`json
374
- ${JSON.stringify(strings.reduce((acc, s) => {
375
- acc[s.en_string] = '';
376
- return acc;
377
- }, {}), null, 2)}
378
- \`\`\`
379
- `;
380
- // process.env.HEAVY_DEBUG && console.log('🧠 llm prompt', prompt);
381
- // call OpenAI
382
- const resp = yield this.options.completeAdapter.complete(prompt, [], 300);
383
- // process.env.HEAVY_DEBUG && console.log('🧠 llm resp', resp);
384
- if (resp.error) {
385
- throw new AiTranslateError(resp.error);
386
- }
387
- // parse response like
388
- // Here are the translations for the strings you provided:
389
- // ```json
390
- // [{"live": "canlı"}, {"Table Games": "Masa Oyunları"}]
391
- // ```
392
- let res;
393
- try {
394
- res = resp.content.split("```json")[1].split("```")[0];
395
- }
396
- catch (e) {
397
- console.error('error in parsing OpenAI', resp);
398
- throw new AiTranslateError('Error in parsing OpenAI response');
399
- }
400
- res = JSON.parse(res);
401
- for (const [enStr, translatedStr] of Object.entries(res)) {
402
- const translationsTargeted = translations.filter(t => t[this.enFieldName] === enStr);
403
- // might be several with same en_string
404
- for (const translation of translationsTargeted) {
405
- //translation[this.trFieldNames[lang]] = translatedStr;
406
- // process.env.HEAVY_DEBUG && console.log(`🪲translated to ${lang} ${translation.en_string}, ${translatedStr}`)
407
- if (!updateStrings[translation[this.primaryKeyFieldName]]) {
408
- updateStrings[translation[this.primaryKeyFieldName]] = {
409
- updates: {},
410
- translatedStr,
411
- category: translation[this.options.categoryFieldName],
412
- strId: translation[this.primaryKeyFieldName],
413
- };
414
- }
415
- updateStrings[translation[this.primaryKeyFieldName]].updates[this.trFieldNames[lang]] = translatedStr;
416
- }
417
- }
418
- return Object.keys(updateStrings);
419
- });
420
426
  const langsInvolved = new Set(Object.keys(needToTranslateByLang));
421
427
  let totalTranslated = [];
428
+ process.env.HEAVY_DEBUG && console.log(' 🐛starting Promise.all Object.entries(needToTranslateByLang)');
422
429
  yield Promise.all(Object.entries(needToTranslateByLang).map((_b) => __awaiter(this, [_b], void 0, function* ([lang, strings]) {
423
430
  // first translate without plurals
424
431
  const stringsWithoutPlurals = strings.filter(s => !s.en_string.includes('|'));
425
432
  process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} noplurals started ${stringsWithoutPlurals.length}`);
426
- const noPluralKeys = yield translateToLang(lang, stringsWithoutPlurals, false);
433
+ const noPluralKeys = yield this.translateToLang(lang, stringsWithoutPlurals, false, translations, updateStrings);
427
434
  process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} noplurals finished`);
428
435
  const stringsWithPlurals = strings.filter(s => s.en_string.includes('|'));
429
436
  process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} plurals started ${stringsWithPlurals.length}`);
430
- const pluralKeys = yield translateToLang(lang, stringsWithPlurals, true);
437
+ const pluralKeys = yield this.translateToLang(lang, stringsWithPlurals, true, translations, updateStrings);
431
438
  process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} plurals finished`);
432
439
  totalTranslated = totalTranslated.concat(noPluralKeys, pluralKeys);
433
440
  })));
434
- process.env.HEAVY_DEBUG && console.log('updateStrings were formed', totalTranslated);
441
+ process.env.HEAVY_DEBUG && console.log('updateStrings were formed', (new Set(totalTranslated)));
435
442
  yield Promise.all(Object.entries(updateStrings).map((_c) => __awaiter(this, [_c], void 0, function* ([_, { updates, strId }]) {
436
443
  // because this will translate all languages, we can set completedLangs to all languages
437
444
  const futureCompletedFieldValue = this.fullCompleatedFieldValue;
package/index.ts CHANGED
@@ -7,6 +7,11 @@ import fs from 'fs-extra';
7
7
  import chokidar from 'chokidar';
8
8
  import { AsyncQueue } from '@sapphire/async-queue';
9
9
 
10
+
11
+ console.log = (...args) => {
12
+ process.stdout.write(args.join(" ") + "\n");
13
+ };
14
+
10
15
  const processFrontendMessagesQueue = new AsyncQueue();
11
16
 
12
17
  const SLAVIC_PLURAL_EXAMPLES = {
@@ -329,7 +334,7 @@ export default class I18N extends AdminForthPlugin {
329
334
  return { ok: false, error: e.message };
330
335
  }
331
336
  }
332
- process.env.HEAVY_DEBUG && console.log('🪲bulkTranslate done', selectedIds);
337
+ process.env.HEAVY_DEBUG && console.log('🪲bulkTranslate done', translatedCount);
333
338
  this.updateUntranslatedMenuBadge();
334
339
  return {
335
340
  ok: true,
@@ -367,6 +372,101 @@ export default class I18N extends AdminForthPlugin {
367
372
  });
368
373
  }
369
374
 
375
+ async translateToLang (
376
+ langIsoCode: LanguageCode,
377
+ strings: { en_string: string, category: string }[],
378
+ plurals=false,
379
+ translations: any[],
380
+ updateStrings: Record<string, { updates: any, category: string, strId: string, translatedStr: string }> = {}
381
+ ): Promise<string[]> {
382
+ const maxKeysInOneReq = 10;
383
+ if (strings.length === 0) {
384
+ return [];
385
+ }
386
+
387
+ if (strings.length > maxKeysInOneReq) {
388
+ let totalTranslated = [];
389
+ for (let i = 0; i < strings.length; i += maxKeysInOneReq) {
390
+ const slicedStrings = strings.slice(i, i + maxKeysInOneReq);
391
+ process.env.HEAVY_DEBUG && console.log('🪲🔪slicedStrings len', slicedStrings.length);
392
+ const madeKeys = await this.translateToLang(langIsoCode, slicedStrings, plurals, translations, updateStrings);
393
+ totalTranslated = totalTranslated.concat(madeKeys);
394
+ }
395
+ return totalTranslated;
396
+ }
397
+ const lang = langIsoCode;
398
+
399
+ const requestSlavicPlurals = Object.keys(SLAVIC_PLURAL_EXAMPLES).includes(lang) && plurals;
400
+
401
+ const prompt = `
402
+ I need to translate strings in JSON to ${lang} language from English for my web app.
403
+ ${requestSlavicPlurals ? `You should provide 4 translations (in format zero | singular | 2-4 | 5+) e.g. ${SLAVIC_PLURAL_EXAMPLES[lang]}` : ''}
404
+ Keep keys, as is, write translation into values! Here are the strings:
405
+
406
+ \`\`\`json
407
+ ${
408
+ JSON.stringify(strings.reduce((acc: object, s: { en_string: string }): object => {
409
+ acc[s.en_string] = '';
410
+ return acc;
411
+ }, {}), null, 2)
412
+ }
413
+ \`\`\`
414
+ `;
415
+
416
+ // process.env.HEAVY_DEBUG && console.log('🧠 llm prompt', prompt);
417
+
418
+ // call OpenAI
419
+ const resp = await this.options.completeAdapter.complete(
420
+ prompt,
421
+ [],
422
+ 300,
423
+ );
424
+
425
+ // process.env.HEAVY_DEBUG && console.log('🧠 llm resp', resp);
426
+
427
+ if (resp.error) {
428
+ throw new AiTranslateError(resp.error);
429
+ }
430
+
431
+ // parse response like
432
+ // Here are the translations for the strings you provided:
433
+ // ```json
434
+ // [{"live": "canlı"}, {"Table Games": "Masa Oyunları"}]
435
+ // ```
436
+ let res;
437
+ try {
438
+ res = resp.content.split("```json")[1].split("```")[0];
439
+ } catch (e) {
440
+ console.error('error in parsing OpenAI', resp);
441
+ throw new AiTranslateError('Error in parsing OpenAI response');
442
+ }
443
+ res = JSON.parse(res);
444
+
445
+
446
+ for (const [enStr, translatedStr] of Object.entries(res) as [string, string][]) {
447
+ const translationsTargeted = translations.filter(t => t[this.enFieldName] === enStr);
448
+ // might be several with same en_string
449
+ for (const translation of translationsTargeted) {
450
+ //translation[this.trFieldNames[lang]] = translatedStr;
451
+ // process.env.HEAVY_DEBUG && console.log(`🪲translated to ${lang} ${translation.en_string}, ${translatedStr}`)
452
+ if (!updateStrings[translation[this.primaryKeyFieldName]]) {
453
+
454
+ updateStrings[translation[this.primaryKeyFieldName]] = {
455
+ updates: {},
456
+ translatedStr,
457
+ category: translation[this.options.categoryFieldName],
458
+ strId: translation[this.primaryKeyFieldName],
459
+ };
460
+ }
461
+ updateStrings[
462
+ translation[this.primaryKeyFieldName]
463
+ ].updates[this.trFieldNames[lang]] = translatedStr;
464
+ }
465
+ }
466
+
467
+ return Object.keys(updateStrings);
468
+ }
469
+
370
470
  // returns translated count
371
471
  async bulkTranslate({ selectedIds }: { selectedIds: string[] }): Promise<number> {
372
472
 
@@ -409,115 +509,34 @@ export default class I18N extends AdminForthPlugin {
409
509
  translatedStr: string
410
510
  }> = {};
411
511
 
412
- const translateToLang = async (langIsoCode: LanguageCode, strings: { en_string: string, category: string }[], plurals=false): Promise<string[]> => {
413
- if (strings.length === 0) {
414
- return [];
415
- }
416
-
417
- if (strings.length > maxKeysInOneReq) {
418
- let totalTranslated = [];
419
- for (let i = 0; i < strings.length; i += maxKeysInOneReq) {
420
- const slicedStrings = strings.slice(i, i + maxKeysInOneReq);
421
- process.env.HEAVY_DEBUG && console.log('🪲🔪slicedStrings len', slicedStrings.length);
422
- const madeKeys = await translateToLang(langIsoCode, slicedStrings, plurals);
423
- totalTranslated = totalTranslated.concat(madeKeys);
424
- }
425
- return totalTranslated;
426
- }
427
- const lang = langIsoCode;
428
-
429
- const requestSlavicPlurals = Object.keys(SLAVIC_PLURAL_EXAMPLES).includes(lang) && plurals;
430
-
431
- const prompt = `
432
- I need to translate strings in JSON to ${lang} language from English for my web app.
433
- ${requestSlavicPlurals ? `You should provide 4 translations (in format zero | singular | 2-4 | 5+) e.g. ${SLAVIC_PLURAL_EXAMPLES[lang]}` : ''}
434
- Keep keys, as is, write translation into values! Here are the strings:
435
-
436
- \`\`\`json
437
- ${
438
- JSON.stringify(strings.reduce((acc: object, s: { en_string: string }): object => {
439
- acc[s.en_string] = '';
440
- return acc;
441
- }, {}), null, 2)
442
- }
443
- \`\`\`
444
- `;
445
-
446
- // process.env.HEAVY_DEBUG && console.log('🧠 llm prompt', prompt);
447
-
448
- // call OpenAI
449
- const resp = await this.options.completeAdapter.complete(
450
- prompt,
451
- [],
452
- 300,
453
- );
454
-
455
- // process.env.HEAVY_DEBUG && console.log('🧠 llm resp', resp);
456
-
457
- if (resp.error) {
458
- throw new AiTranslateError(resp.error);
459
- }
460
-
461
- // parse response like
462
- // Here are the translations for the strings you provided:
463
- // ```json
464
- // [{"live": "canlı"}, {"Table Games": "Masa Oyunları"}]
465
- // ```
466
- let res;
467
- try {
468
- res = resp.content.split("```json")[1].split("```")[0];
469
- } catch (e) {
470
- console.error('error in parsing OpenAI', resp);
471
- throw new AiTranslateError('Error in parsing OpenAI response');
472
- }
473
- res = JSON.parse(res);
474
-
475
-
476
- for (const [enStr, translatedStr] of Object.entries(res) as [string, string][]) {
477
- const translationsTargeted = translations.filter(t => t[this.enFieldName] === enStr);
478
- // might be several with same en_string
479
- for (const translation of translationsTargeted) {
480
- //translation[this.trFieldNames[lang]] = translatedStr;
481
- // process.env.HEAVY_DEBUG && console.log(`🪲translated to ${lang} ${translation.en_string}, ${translatedStr}`)
482
- if (!updateStrings[translation[this.primaryKeyFieldName]]) {
483
-
484
- updateStrings[translation[this.primaryKeyFieldName]] = {
485
- updates: {},
486
- translatedStr,
487
- category: translation[this.options.categoryFieldName],
488
- strId: translation[this.primaryKeyFieldName],
489
- };
490
- }
491
- updateStrings[
492
- translation[this.primaryKeyFieldName]
493
- ].updates[this.trFieldNames[lang]] = translatedStr;
494
- }
495
- }
496
-
497
- return Object.keys(updateStrings);
498
- }
499
512
 
500
513
  const langsInvolved = new Set(Object.keys(needToTranslateByLang));
501
514
 
502
515
  let totalTranslated = [];
503
- await Promise.all(Object.entries(needToTranslateByLang).map(async ([lang, strings]: [LanguageCode, { en_string: string, category: string }[]]) => {
504
- // first translate without plurals
505
- const stringsWithoutPlurals = strings.filter(s => !s.en_string.includes('|'));
506
- process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} noplurals started ${stringsWithoutPlurals.length}`);
507
- const noPluralKeys = await translateToLang(lang, stringsWithoutPlurals, false);
508
- process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} noplurals finished`);
516
+ process.env.HEAVY_DEBUG && console.log(' 🐛starting Promise.all Object.entries(needToTranslateByLang)');
509
517
 
518
+ await Promise.all(
519
+ Object.entries(needToTranslateByLang).map(
520
+ async ([lang, strings]: [LanguageCode, { en_string: string, category: string }[]]) => {
521
+ // first translate without plurals
522
+ const stringsWithoutPlurals = strings.filter(s => !s.en_string.includes('|'));
523
+ process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} noplurals started ${stringsWithoutPlurals.length}`);
524
+ const noPluralKeys = await this.translateToLang(lang, stringsWithoutPlurals, false, translations, updateStrings);
525
+ process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} noplurals finished`);
510
526
 
511
- const stringsWithPlurals = strings.filter(s => s.en_string.includes('|'));
512
527
 
513
- process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} plurals started ${stringsWithPlurals.length}`);
514
- const pluralKeys = await translateToLang(lang, stringsWithPlurals, true);
515
- process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} plurals finished`);
528
+ const stringsWithPlurals = strings.filter(s => s.en_string.includes('|'));
516
529
 
517
- totalTranslated = totalTranslated.concat(noPluralKeys, pluralKeys);
518
- }));
530
+ process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} plurals started ${stringsWithPlurals.length}`);
531
+ const pluralKeys = await this.translateToLang(lang, stringsWithPlurals, true, translations, updateStrings);
532
+ process.env.HEAVY_DEBUG && console.log(`🔗 ${lang} plurals finished`);
533
+
534
+ totalTranslated = totalTranslated.concat(noPluralKeys, pluralKeys);
535
+ }
536
+ )
537
+ );
519
538
 
520
- process.env.HEAVY_DEBUG && console.log('updateStrings were formed', totalTranslated);
539
+ process.env.HEAVY_DEBUG && console.log('updateStrings were formed', (new Set(totalTranslated)));
521
540
 
522
541
  await Promise.all(
523
542
  Object.entries(updateStrings).map(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/i18n",
3
- "version": "1.0.18-next.5",
3
+ "version": "1.0.18-next.7",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",