forked from cyon/vue-translation-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
369 lines (308 loc) · 11.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
const fs = require('fs')
const path = require('path')
const execall = require('execall')
const glob = require('glob')
const uniq = require('lodash.uniq')
const { transliterate } = require('transliteration');
const inquirer = require('inquirer');
/**
* Initialize the translation manager
* @param {object} opts Options
* @param {array} opts.languages The languages, e.g. ["en", "de"]
* @param {object} opts.adapter Adapter for storing and accessing the translations
* @param {string} opts.path Path to the translations
*/
function TranslationManager (opts) {
this.languages = opts.languages || []
if (this.languages.length === 0) throw new Error('No languages given')
this.adapter = opts.adapter
if (!this.adapter) throw new Error('No adapter given')
this.srcPath = opts.srcPath || process.cwd()
this.rootPath = opts.root || process.cwd()
this.adapter._setLanguages(this.languages)
}
module.exports = TranslationManager
module.exports.JSONAdapter = require('./adapter-json.js')
/**
* Get the languages configured
* @returns {array}
*/
TranslationManager.prototype.getLanguages = function () {
return this.languages
}
/**
* Get the configured src path
* @returns {string}
*/
TranslationManager.prototype.getSrcPath = function () {
return this.srcPath
}
/**
* Get the template part for a vue component
* @param {string} path Path to the vue single file component, null if there is none
* @returns {object}
*/
TranslationManager.prototype.getTemplateForSingleFileComponent = function (path) {
const contents = fs.readFileSync(path, { encoding: 'utf8' })
const templateResult = /<template>([\w\W]*)<\/template>/g.exec(contents)
if (!templateResult) return null
let template = ''
if (templateResult && templateResult[1]) template = templateResult[1]
return { template: template, offset: templateResult[0].indexOf(templateResult[1]) + templateResult.index }
}
/**
* Get all untranslated strings for a given vue component
* @param {string} pathToComponent Path to the vue component
*/
TranslationManager.prototype.getStringsForComponent = function (pathToComponent) {
var templateResult = this.getTemplateForSingleFileComponent(pathToComponent)
if (!templateResult) return []
var templateOffset = templateResult.offset
var template = templateResult.template
var matches = execall(/>([^<>]*)</gm, template)
function extractTemplateExpression (text) {
const indexOfOpening = text.indexOf('{{')
const indexOfClosing = text.indexOf('}}')
if (indexOfClosing === -1 || indexOfOpening === -1) {
return {
expression: null,
text: text
}
}
return {
index: indexOfOpening,
indexClosing: indexOfClosing,
expression: text.substring(indexOfOpening + 2, indexOfClosing).trim(),
text: '' + text.substring(0, indexOfOpening) + text.substring(indexOfClosing + 2)
}
}
function checkTemplateExpression (text) {
let currText = text
let expression = true
let expressions = []
let currentOffset = 0
while (expression !== null) {
let result = extractTemplateExpression(currText)
currText = result.text
expression = result.expression
if (expression !== null) {
expressions.push({
expr: expression,
indexStart: currentOffset + result.index,
indexEnd: currentOffset + result.indexClosing
})
currentOffset += (result.indexClosing - result.index) + 2
}
}
return {
staticText: currText.trim(),
hasStaticText: currText.trim().length > 0,
expressions
}
}
var textNodeMatches = matches.map((match) => {
let expressionsInfo = checkTemplateExpression(match.sub[0])
if (!expressionsInfo.hasStaticText) return
if (expressionsInfo.staticText.length < 3) return
return {
indexInTemplate: match.index + 1,
indexInFile: templateOffset + match.index + 1,
originalString: match.sub[0],
string: expressionsInfo.staticText,
stringLength: match.sub[0].length,
expressions: expressionsInfo.expressions,
where: 'textNode'
}
}).filter(Boolean)
var attributeResults = execall(/\s([a-z]*-)?(title|label|text|caption|placeholder)="([^"]*)"/gm, template)
var attributeMatches = attributeResults.map((match) => {
if (!match.sub[2] || match.sub[2].trim() === '') return
return {
indexInTemplate: match.index + match.match.indexOf(match.sub[2]),
indexInFile: templateOffset + match.index + match.match.indexOf(match.sub[2]),
originalString: match.sub[2].trim(),
string: match.sub[2].trim(),
stringLength: match.sub[2].length,
expressions: [],
where: 'attribute'
}
}).filter(Boolean)
return textNodeMatches.concat(...attributeMatches).sort((a, b) => {
if (a.indexInFile < b.indexInFile) return -1
if (a.indexInFile > b.indexInFile) return 1
return 0
})
}
/**
* Replace untranslated strings with their corresponding $t function call
* @param {string} pathToComponent Path to the vue component
* @param {array} strings The strings to replace
*/
TranslationManager.prototype.replaceStringsInComponent = function (pathToComponent, strings) {
var fileContents = fs.readFileSync(pathToComponent, { encoding: 'utf8' })
var contentsAfter = fileContents
var offset = 0
strings.map((str) => {
var translateFn = `{{ $t('${str.key}') }}`
if (str.expressions.length > 0) {
var params = []
for (var i = 0; i < str.expressions.length; i++) {
params.push(`'${i + 1}': ${str.expressions[i].expr}`)
}
translateFn = `{{ $t('${str.key}', { ${params.join(', ')} }) }}`
}
var firstPart = contentsAfter.substring(0, offset + str.indexInFile)
var secondPart = contentsAfter.substring(offset + str.indexInFile + str.stringLength)
if (str.where === 'attribute') {
translateFn = `$t('${str.key}')`
firstPart = firstPart.substring(0, firstPart.lastIndexOf(' ') + 1) + ':' + firstPart.substring(firstPart.lastIndexOf(' ') + 1)
offset += 1
}
contentsAfter = `${firstPart}${translateFn}${secondPart}`
offset += (translateFn.length - str.stringLength)
})
fs.writeFileSync(pathToComponent, contentsAfter)
}
/**
* Prompt the user to input a custom translation key for a given text, or use a suggested key if none is provided.
* The key is generated based on the transliterated and formatted text, avoiding duplicates by checking used keys.
* @param {string} pathToFile - The path of the file where the translation will be used.
* @param {string} text - The text that requires translation.
* @param {array} usedKeys - (Optional) An array of keys that have already been used, to prevent duplicates.
* @returns {Promise<string>} - The chosen or generated translation key.
*/
TranslationManager.prototype.getSuggestedKey = async function (pathToFile, text, usedKeys) {
const words = text.trim().split(' ');
const limitedWords = words.length > 7 ? words.slice(0, 6) : words;
let word = limitedWords
.map(w => transliterate(w).toUpperCase().replace(/[^A-Z_0-9]/g, ''))
.filter(w => w)
.join('_');
if (!word) word = `UNDEFINED_STRING_${Math.floor(Math.random() * 10000)}`;
const generatedKey = await this.getCompatibleKey(`${word}`, usedKeys);
const prompt = inquirer.createPromptModule();
const answer = await prompt({
type: 'input',
name: 'customKey',
message: `Enter a custom key for "${text}" (or press Enter to use "${generatedKey}"): `,
default: generatedKey
});
// Преобразуем введенный ключ в формат с заглавными буквами и подчеркиваниями
const customKey = answer.customKey || generatedKey;
const formattedKey = customKey
.replace(/\s+/g, '_') // Заменяем пробелы на подчеркивания
.toUpperCase() // Переводим все буквы в верхний регистр
.replace(/[^A-Z_0-9]/g, ''); // Убираем все недопустимые символы
return formattedKey;
};
TranslationManager.prototype.getCompatibleKey = async function (suggestedKey, usedKeys) {
let keys = await this.adapter.getAllKeys()
keys = Object.keys(keys).reduce((map, lang) => {
return map.concat(keys[lang])
}, [])
if (usedKeys && typeof Array.isArray(usedKeys)) {
keys = keys.concat(usedKeys)
}
let twitchIt = () => {
return keys.some((key) => {
let existingCheck = new RegExp('^(' + suggestedKey.replace(/\./g, '\\.') + ')(\\..*)?$')
let existingMatch = key.match(existingCheck)
if (existingMatch) {
let secondPart = suggestedKey.substring(existingMatch[1].length)
suggestedKey = `${increaseTrailingNumber(existingMatch[1])}${secondPart}`
return true
}
let reg = new RegExp('^' + key.replace(/\./g, '\\.') + '(\\..*)?$')
let match = suggestedKey.match(reg)
if (!match) return false
suggestedKey = increaseTrailingNumber(suggestedKey)
return true
})
}
while (twitchIt()) {}
return suggestedKey
}
/**
* Add a translated string to a messages resource
* @param {string} key The key for which the strings will be saved
* @param {object} translations Keys are the languages (e.g. "en", "de"), the values are the translated strings
*/
TranslationManager.prototype.addTranslatedString = function (key, translations) {
return this.adapter.addTranslations(key, translations)
}
TranslationManager.prototype.getUnusedTranslations = async function () {
var unusedTranslations = []
let allKeys = []
let keysInLanguages = await this.adapter.getAllKeys()
Object.keys(keysInLanguages).map((lang) => {
allKeys = allKeys.concat(keysInLanguages[lang])
})
allKeys = uniq(allKeys)
allKeys.map((translationKey) => {
var usages = this.getTranslationUsages(translationKey)
if (usages.length === 0) unusedTranslations.push(translationKey)
})
return unusedTranslations
}
TranslationManager.prototype.getTranslationsForKey = async function (key) {
return this.adapter.getTranslations(key)
}
TranslationManager.prototype.deleteTranslations = async function (key) {
return this.adapter.deleteTranslations([key])
}
TranslationManager.prototype.getTranslationUsages = function (translationKey) {
var files = glob.sync(`${this.srcPath}/**/*.vue`)
var usages = []
files.map((file) => {
var fileContents = fs.readFileSync(file)
if (fileContents.indexOf(`$t('${translationKey}'`) > -1) usages.push(file)
if (fileContents.indexOf(`$t("${translationKey}"`) > -1) usages.push(file)
})
return usages
}
TranslationManager.prototype.validate = async function () {
let missingKeys = {}
let allKeys = []
let keysInLanguages = await this.adapter.getAllKeys()
Object.keys(keysInLanguages).map((lang) => {
allKeys = allKeys.concat(keysInLanguages[lang])
})
allKeys = uniq(allKeys)
this.languages.forEach((lang) => {
for (let key of allKeys) {
if (!keysInLanguages[lang].includes(key)) {
if (!missingKeys.hasOwnProperty(lang)) {
missingKeys[lang] = []
}
missingKeys[lang].push(key)
}
}
})
return missingKeys
}
/**
* camelCase any string
* @param {string} text The string to be camelCased
* @returns {string} theStringInCamelCase
*/
function camelCase (text) {
return text
.trim()
.split(' ')
.map((word) => word.toLowerCase())
.map((word, i) => (i === 0 ? word : word[0].toUpperCase() + word.substring(1)))
.join('')
}
function increaseTrailingNumber (str) {
let chars = str.split('')
chars.reverse()
let numbers = 0
for (var i = 0; i < chars.length; i++) {
if (!isNaN(parseInt(chars[i]))) numbers++
break
}
chars = chars.reverse().join('')
let keyWithoutNumber = chars.substring(0, chars.length - numbers)
let currentNumber = parseInt(chars.substring(chars.length - numbers)) || 0
return `${keyWithoutNumber}${++currentNumber}`
}