auto-translate-json-library 1.0.2 → 1.0.3

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/index.js ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.translate = void 0;
4
+ const lib_1 = require("./lib");
5
+ Object.defineProperty(exports, "translate", { enumerable: true, get: function () { return lib_1.translate; } });
6
+ let config = {};
7
+ require('dotenv').config();
8
+ if (process.env.ATJ_GOOGLE_API_KEY) {
9
+ config.translationKeyInfo = {
10
+ kind: 'google',
11
+ apiKey: process.env.ATJ_GOOGLE_API_KEY,
12
+ };
13
+ }
14
+ if (process.env.ATJ_AWS_ACCESS_KEY_ID &&
15
+ process.env.ATJ_AWS_SECRET_ACCESS_KEY &&
16
+ process.env.ATJ_AWS_REGION) {
17
+ config.translationKeyInfo = {
18
+ kind: 'aws',
19
+ accessKeyId: process.env.ATJ_AWS_ACCESS_KEY_ID,
20
+ secretAccessKey: process.env.ATJ_AWS_SECRET_ACCESS_KEY,
21
+ region: process.env.ATJ_AWS_REGION,
22
+ };
23
+ }
24
+ if (process.env.ATJ_AZURE_SECRET_KEY && process.env.ATJ_AZURE_REGION) {
25
+ config.translationKeyInfo = {
26
+ kind: 'azure',
27
+ secretKey: process.env.ATJ_AZURE_SECRET_KEY,
28
+ region: process.env.ATJ_AZURE_REGION,
29
+ };
30
+ }
31
+ if (process.env.ATJ_DEEPL_PRO_SECRET_KEY) {
32
+ config.translationKeyInfo = {
33
+ kind: 'deepLPro',
34
+ secretKey: process.env.ATJ_DEEPL_PRO_SECRET_KEY,
35
+ };
36
+ }
37
+ if (process.env.ATJ_DEEPL_FREE_SECRET_KEY) {
38
+ config.translationKeyInfo = {
39
+ kind: 'deepLFree',
40
+ secretKey: process.env.ATJ_DEEPL_FREE_SECRET_KEY,
41
+ };
42
+ }
43
+ if (process.env.ATJ_START_DELIMITER) {
44
+ config.startDelimiter = process.env.ATJ_START_DELIMITER;
45
+ }
46
+ if (process.env.ATJ_END_DELIMITER) {
47
+ config.endDelimiter = process.env.ATJ_END_DELIMITER;
48
+ }
49
+ if (process.env.ATJ_END_DELIMITER) {
50
+ config.endDelimiter = process.env.ATJ_END_DELIMITER;
51
+ }
52
+ if (process.env.ATJ_MODE &&
53
+ (process.env.ATJ_MODE === 'file' || process.env.ATJ_MODE === 'folder')) {
54
+ config.mode = process.env.ATJ_MODE;
55
+ }
56
+ if (process.env.ATJ_SOURCE_LOCALE) {
57
+ config.sourceLocale = process.env.ATJ_SOURCE_LOCALE;
58
+ }
59
+ if (process.env.ATJ_KEEP_TRANSLATIONS &&
60
+ (process.env.ATJ_KEEP_TRANSLATIONS === 'keep' ||
61
+ process.env.ATJ_KEEP_TRANSLATIONS === 'retranslate')) {
62
+ config.keepTranslations = process.env.ATJ_KEEP_TRANSLATIONS;
63
+ }
64
+ if (process.env.ATJ_KEEP_EXTRA_TRANSLATIONS &&
65
+ (process.env.ATJ_KEEP_EXTRA_TRANSLATIONS === 'keep' ||
66
+ process.env.ATJ_KEEP_EXTRA_TRANSLATIONS === 'remove')) {
67
+ config.keepExtraTranslations = process.env.ATJ_KEEP_EXTRA_TRANSLATIONS;
68
+ }
69
+ console.log(config);
70
+ var args = process.argv.slice(2);
71
+ console.log(args);
72
+ console.log(__dirname);
73
+ console.log(process.cwd());
74
+ if (args.length > 0) {
75
+ (0, lib_1.translate)(args[0], config);
76
+ }
package/lib.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { Configuration } from './config';
2
+ export declare function translate(sourceFile: string, config: Configuration): Promise<void>;
package/lib.js ADDED
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.translate = void 0;
13
+ // The module 'vscode' contains the VS Code extensibility API
14
+ // Import the module and reference it with the alias vscode in your code below
15
+ const files_1 = require("./files");
16
+ const folderFiles_1 = require("./folderFiles");
17
+ const aws_1 = require("./aws");
18
+ const azure_1 = require("./azure");
19
+ const google_1 = require("./google");
20
+ const util_1 = require("./util");
21
+ const deepl_1 = require("./deepl");
22
+ const NAME = 'AutoTranslateJSON';
23
+ function translate(sourceFile, config) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ // set the delimiters for named arguments
26
+ const startDelimiter = config.startDelimiter || '{';
27
+ if (startDelimiter) {
28
+ util_1.Util.startDelimiter = startDelimiter;
29
+ }
30
+ const endDelimiter = config.endDelimiter || '}';
31
+ if (endDelimiter) {
32
+ util_1.Util.endDelimiter = endDelimiter;
33
+ }
34
+ let translateEngine;
35
+ if (config.translationKeyInfo.kind === 'google') {
36
+ translateEngine = new google_1.GoogleTranslate(config.translationKeyInfo.apiKey);
37
+ }
38
+ else if (config.translationKeyInfo.kind === 'aws') {
39
+ translateEngine = new aws_1.AWSTranslate(config.translationKeyInfo.accessKeyId, config.translationKeyInfo.secretAccessKey, config.translationKeyInfo.region);
40
+ }
41
+ else if (config.translationKeyInfo.kind === 'azure') {
42
+ translateEngine = new azure_1.AzureTranslate(config.translationKeyInfo.secretKey, config.translationKeyInfo.region);
43
+ }
44
+ else if (config.translationKeyInfo.kind === 'deepLFree') {
45
+ translateEngine = new deepl_1.DeepLTranslate(config.translationKeyInfo.secretKey, 'free');
46
+ }
47
+ else if (config.translationKeyInfo.kind === 'deepLPro') {
48
+ translateEngine = new deepl_1.DeepLTranslate(config.translationKeyInfo.secretKey, 'pro');
49
+ }
50
+ else {
51
+ console.warn('You must provide a Google, AWS or Azure parameters first in the extension settings.');
52
+ return;
53
+ }
54
+ const fileMode = config.mode;
55
+ const files = readFiles(sourceFile, fileMode);
56
+ if (files === null) {
57
+ return;
58
+ }
59
+ // enforce source locale if provided in settings
60
+ if (config.sourceLocale !== files.sourceLocale) {
61
+ console.log('You must use the ' +
62
+ config.sourceLocale +
63
+ '.json file due to your Source Locale setting.');
64
+ return;
65
+ }
66
+ const keepTranslations = config.keepTranslations === 'keep';
67
+ const keepExtras = config.keepExtraTranslations === 'keep';
68
+ // load source JSON
69
+ let source;
70
+ try {
71
+ source = yield files.loadJsonFromLocale(files.sourceLocale);
72
+ }
73
+ catch (error) {
74
+ if (error instanceof Error) {
75
+ console.log(error, 'Source file malformed');
76
+ }
77
+ return;
78
+ }
79
+ // Iterate target Locales
80
+ files.targetLocales.forEach((targetLocale) => __awaiter(this, void 0, void 0, function* () {
81
+ try {
82
+ const isValid = yield translateEngine.isValidLocale(targetLocale);
83
+ if (!isValid) {
84
+ throw Error(targetLocale + ' is not supported. Skipping.');
85
+ }
86
+ const targetOriginal = yield files.loadJsonFromLocale(targetLocale);
87
+ // Iterate source terms
88
+ const targetNew = yield recurseNode(source, targetOriginal, keepTranslations, keepExtras, files.sourceLocale, targetLocale, translateEngine);
89
+ // save target
90
+ files.saveJsonToLocale(targetLocale, targetNew);
91
+ const feedback = "Translated locale '" + targetLocale + "'";
92
+ console.log(feedback);
93
+ }
94
+ catch (error) {
95
+ if (error instanceof Error) {
96
+ console.error(error);
97
+ }
98
+ return;
99
+ }
100
+ }));
101
+ });
102
+ }
103
+ exports.translate = translate;
104
+ const readFiles = (filePath, mode) => {
105
+ try {
106
+ const files = mode === 'file' ? new files_1.Files(filePath) : new folderFiles_1.FolderFiles(filePath);
107
+ // log locale info
108
+ console.log('Source locale = ' + files.sourceLocale);
109
+ console.log('Target locales = ' + files.targetLocales);
110
+ return files;
111
+ }
112
+ catch (error) {
113
+ if (error instanceof Error) {
114
+ console.error(error);
115
+ }
116
+ return null;
117
+ }
118
+ };
119
+ function recurseNode(source, original, keepTranslations, keepExtras, sourceLocale, locale, translateEngine, isArray = false) {
120
+ var _a;
121
+ return __awaiter(this, void 0, void 0, function* () {
122
+ const destination = isArray ? [] : {};
123
+ // defaults
124
+ if (keepTranslations === null) {
125
+ keepTranslations = true;
126
+ }
127
+ if (keepExtras === null) {
128
+ keepExtras = true;
129
+ }
130
+ for (const term in source) {
131
+ const node = source[term];
132
+ if (node instanceof Object && node !== null) {
133
+ destination[term] = yield recurseNode(node, (_a = original[term]) !== null && _a !== void 0 ? _a : {}, keepTranslations, keepExtras, sourceLocale, locale, translateEngine, node instanceof Array);
134
+ }
135
+ else {
136
+ // if we already have a translation, keep it
137
+ if (keepTranslations && original[term]) {
138
+ destination[term] = original[term];
139
+ }
140
+ else if (typeof node === 'number' || typeof node === 'boolean') {
141
+ // numbers and booleans do not need translations
142
+ destination[term] = node;
143
+ }
144
+ else {
145
+ const translation = yield translateEngine
146
+ .translateText(node, sourceLocale, locale)
147
+ .catch((err) => console.error(err));
148
+ destination[term] = translation;
149
+ }
150
+ }
151
+ }
152
+ if (keepExtras) {
153
+ // add back in any terms that were not in source
154
+ for (const term in original) {
155
+ if (!destination[term]) {
156
+ destination[term] = original[term];
157
+ }
158
+ }
159
+ }
160
+ return destination;
161
+ });
162
+ }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "auto-translate-json-library",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "",
5
- "main": "./build/index.js",
6
- "types": "./build/index.d.ts",
5
+ "main": "./index.js",
6
+ "types": "./index.d.ts",
7
7
  "scripts": {
8
8
  "prepare": "tsc",
9
9
  "build": "tsc",
@@ -0,0 +1,4 @@
1
+ export interface ITranslate {
2
+ isValidLocale(targetLocale: string): boolean;
3
+ translateText(text: string, sourceLocale: string, targetLocale: string): Promise<string>;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/util.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ export declare class Util {
2
+ private static _startDelimiter;
3
+ private static _endDelimiter;
4
+ private static pattern;
5
+ static set startDelimiter(value: string);
6
+ static set endDelimiter(value: string);
7
+ static replaceArgumentsWithNumbers(args: RegExpMatchArray | null, result: string): string;
8
+ static replaceContextVariables(text: string): {
9
+ args: RegExpMatchArray | null;
10
+ text: string;
11
+ };
12
+ }
package/util.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Util = void 0;
4
+ class Util {
5
+ static set startDelimiter(value) {
6
+ Util._startDelimiter = value;
7
+ // update regex
8
+ Util.pattern = new RegExp(Util._startDelimiter + '(.*?)' + Util._endDelimiter, 'g');
9
+ }
10
+ static set endDelimiter(value) {
11
+ Util._endDelimiter = value;
12
+ // update regex
13
+ Util.pattern = new RegExp(Util._startDelimiter + '(.*?)' + Util._endDelimiter, 'g');
14
+ }
15
+ static replaceArgumentsWithNumbers(args, result) {
16
+ if (args) {
17
+ let i = 0;
18
+ for (let arg of args) {
19
+ result = result.replace(Util._startDelimiter + i + Util._endDelimiter, arg);
20
+ i++;
21
+ }
22
+ }
23
+ return result;
24
+ }
25
+ static replaceContextVariables(text) {
26
+ const args = text.match(Util.pattern);
27
+ // replace arguments with numbers
28
+ if (args) {
29
+ let i = 0;
30
+ for (let arg of args) {
31
+ text = text.replace(arg, Util._startDelimiter + i + Util._endDelimiter);
32
+ i++;
33
+ }
34
+ }
35
+ return { args, text };
36
+ }
37
+ }
38
+ exports.Util = Util;
39
+ Util._startDelimiter = '{';
40
+ Util._endDelimiter = '}';
41
+ Util.pattern = new RegExp(Util._startDelimiter + '(.*?)' + Util._endDelimiter, 'g');
package/src/aws.ts DELETED
@@ -1,133 +0,0 @@
1
- import { ITranslate } from './translate.interface';
2
-
3
- import {
4
- Translate,
5
- TranslateTextCommandInput
6
- } from '@aws-sdk/client-translate';
7
- import { Util } from './util';
8
-
9
- const supportedLanguages = [
10
- 'af',
11
- 'sq',
12
- 'am',
13
- 'ar',
14
- 'hy',
15
- 'az',
16
- 'bn',
17
- 'bs',
18
- 'bg',
19
- 'ca',
20
- 'zh',
21
- 'zh-TW',
22
- 'hr',
23
- 'cs',
24
- 'da',
25
- 'fa-AF',
26
- 'nl',
27
- 'en',
28
- 'et',
29
- 'fa',
30
- 'tl',
31
- 'fi',
32
- 'fr',
33
- 'fr-CA',
34
- 'ka',
35
- 'de',
36
- 'el',
37
- 'gu',
38
- 'ht',
39
- 'ha',
40
- 'he',
41
- 'hi',
42
- 'hu',
43
- 'is',
44
- 'id',
45
- 'ga',
46
- 'it',
47
- 'ja',
48
- 'kn',
49
- 'kk',
50
- 'ko',
51
- 'lv',
52
- 'lt',
53
- 'mk',
54
- 'ms',
55
- 'ml',
56
- 'mt',
57
- 'mr',
58
- 'mn',
59
- 'no',
60
- 'ps',
61
- 'pl',
62
- 'pt',
63
- 'pt-PT',
64
- 'pa',
65
- 'ro',
66
- 'ru',
67
- 'sr',
68
- 'si',
69
- 'sk',
70
- 'sl',
71
- 'so',
72
- 'es',
73
- 'es-MX',
74
- 'sw',
75
- 'sv',
76
- 'ta',
77
- 'te',
78
- 'th',
79
- 'tr',
80
- 'uk',
81
- 'ur',
82
- 'uz',
83
- 'vi',
84
- 'cy'
85
- ];
86
-
87
- export class AWSTranslate implements ITranslate {
88
- private client: Translate;
89
- constructor(
90
- private accessKeyId: string,
91
- private secretAccessKey: string,
92
- private regions: string
93
- ) {
94
- this.client = new Translate({
95
- credentials: {
96
- accessKeyId: this.accessKeyId,
97
- secretAccessKey: this.secretAccessKey
98
- },
99
- region: this.regions
100
- });
101
- }
102
- isValidLocale(targetLocale: string): boolean {
103
- return supportedLanguages.includes(targetLocale);
104
- }
105
- async translateText(
106
- text: string,
107
- sourceLocale: string,
108
- targetLocale: string
109
- ): Promise<string> {
110
- let args;
111
- ({ args, text } = Util.replaceContextVariables(text));
112
-
113
- let result = '';
114
-
115
- const params: TranslateTextCommandInput = {
116
- SourceLanguageCode: sourceLocale,
117
- TargetLanguageCode: targetLocale,
118
- Text: text
119
- };
120
-
121
- try {
122
- const translation = await this.client.translateText(params);
123
- result = translation.TranslatedText as string;
124
- } catch (error) {
125
- console.log(error);
126
- return '';
127
- }
128
-
129
- result = Util.replaceArgumentsWithNumbers(args, result);
130
-
131
- return result;
132
- }
133
- }
package/src/azure.ts DELETED
@@ -1,169 +0,0 @@
1
- import { ITranslate } from './translate.interface';
2
- import { Util } from './util';
3
-
4
- const axios = require('axios').default;
5
- const { v4: uuidv4 } = require('uuid');
6
-
7
- const supportedLanguages = [
8
- 'af',
9
- 'sq',
10
- 'am',
11
- 'ar',
12
- 'hy',
13
- 'as',
14
- 'az',
15
- 'bn',
16
- 'ba',
17
- 'bs',
18
- 'bg',
19
- 'yue',
20
- 'ca',
21
- 'lzh',
22
- 'zh-Hans',
23
- 'zh-Hant',
24
- 'hr',
25
- 'cs',
26
- 'da',
27
- 'prs',
28
- 'dv',
29
- 'nl',
30
- 'en',
31
- 'et',
32
- 'fj',
33
- 'fil',
34
- 'fi',
35
- 'fr',
36
- 'fr-ca',
37
- 'ka',
38
- 'de',
39
- 'el',
40
- 'gu',
41
- 'ht',
42
- 'he',
43
- 'hi',
44
- 'mww',
45
- 'hu',
46
- 'is',
47
- 'id',
48
- 'iu',
49
- 'ga',
50
- 'it',
51
- 'ja',
52
- 'kn',
53
- 'kk',
54
- 'km',
55
- 'tlh-Latn',
56
- 'tlh-Piqd',
57
- 'ko',
58
- 'ku',
59
- 'kmr',
60
- 'ky',
61
- 'lo',
62
- 'lv',
63
- 'lt',
64
- 'mk',
65
- 'mg',
66
- 'ms',
67
- 'ml',
68
- 'mt',
69
- 'mi',
70
- 'mr',
71
- 'mn-Cyrl',
72
- 'mn-Mong',
73
- 'my',
74
- 'ne',
75
- 'nb',
76
- 'or',
77
- 'ps',
78
- 'fa',
79
- 'pl',
80
- 'pt',
81
- 'pt-pt',
82
- 'pa',
83
- 'otq',
84
- 'ro',
85
- 'ru',
86
- 'sm',
87
- 'sr-Cyrl',
88
- 'sr-Latn',
89
- 'sk',
90
- 'sl',
91
- 'es',
92
- 'sw',
93
- 'sv',
94
- 'ty',
95
- 'ta',
96
- 'tt',
97
- 'te',
98
- 'th',
99
- 'bo',
100
- 'ti',
101
- 'to',
102
- 'tr',
103
- 'tk',
104
- 'uk',
105
- 'ur',
106
- 'ug',
107
- 'uz',
108
- 'vi',
109
- 'cy',
110
- 'yua'
111
- ];
112
-
113
- export class AzureTranslate implements ITranslate {
114
- private endpoint = 'https://api.cognitive.microsofttranslator.com';
115
- constructor(
116
- private subscriptionKey: string,
117
- private subscriptionRegion: string
118
- ) {}
119
- isValidLocale(targetLocale: string): boolean {
120
- return supportedLanguages.includes(targetLocale);
121
- }
122
- async translateText(
123
- text: string,
124
- sourceLocale: string,
125
- targetLocale: string
126
- ): Promise<string> {
127
- let args;
128
- ({ args, text } = Util.replaceContextVariables(text));
129
-
130
- let result = '';
131
-
132
- const response = await axios({
133
- baseURL: this.endpoint,
134
- url: '/translate',
135
- method: 'post',
136
- headers: {
137
- 'Ocp-Apim-Subscription-Key': this.subscriptionKey,
138
- 'Ocp-Apim-Subscription-Region': this.subscriptionRegion,
139
- 'Content-type': 'application/json',
140
- 'X-ClientTraceId': uuidv4().toString()
141
- },
142
- params: {
143
- 'api-version': '3.0',
144
- from: sourceLocale,
145
- to: [targetLocale]
146
- },
147
- data: [
148
- {
149
- text: text
150
- }
151
- ],
152
- responseType: 'json'
153
- });
154
- result = response.data[0].translations[0].text;
155
-
156
- result = Util.replaceArgumentsWithNumbers(args, result);
157
-
158
- return result;
159
- }
160
- }
161
-
162
- // https://docs.microsoft.com/en-us/azure/cognitive-services/translator/quickstart-translator?tabs=nodejs#translate-text
163
-
164
- // Add your location, also known as region. The default is global.
165
- // This is required if using a Cognitive Services resource.
166
-
167
- /*
168
-
169
- */
package/src/config.ts DELETED
@@ -1,37 +0,0 @@
1
- export type Configuration = {
2
- translationKeyInfo:
3
- | GoogleTranslationKey
4
- | AwsTranslationKey
5
- | AzureTranslationKey
6
- | DeepLProTranslationKey
7
- | DeepLFreeTranslationKey;
8
- startDelimiter: string;
9
- endDelimiter: string;
10
- mode: 'file' | 'folder';
11
- sourceLocale: string;
12
- keepTranslations: 'keep' | 'retranslate';
13
- keepExtraTranslations: 'keep' | 'remove';
14
- };
15
-
16
- type GoogleTranslationKey = { kind: 'google'; apiKey: string };
17
- type AwsTranslationKey = {
18
- kind: 'aws';
19
- accessKeyId: string;
20
- secretAccessKey: string;
21
- region: string;
22
- };
23
- type AzureTranslationKey = {
24
- kind: 'azure';
25
- secretKey: string;
26
- region: string;
27
- };
28
- type DeepLProTranslationKey = {
29
- kind: 'deepLPro';
30
- secretKey: string;
31
- };
32
-
33
- type DeepLFreeTranslationKey = {
34
- kind: 'deepLFree';
35
- secretKey: string;
36
- };
37
-