i18n.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. const fs = require('fs').promises;
  2. const path = require('path');
  3. const Vinyl = require('vinyl');
  4. const PluginError = require('plugin-error');
  5. const through = require('through2');
  6. const yaml = require('js-yaml');
  7. const transformers = {
  8. '.yml': data => yaml.safeLoad(data),
  9. '.json': data => JSON.parse(data),
  10. };
  11. class Locale {
  12. constructor(lang, base) {
  13. this.defaultLocale = 'messages.yml';
  14. this.lang = lang;
  15. this.base = base;
  16. this.data = {};
  17. this.desc = {};
  18. }
  19. async load() {
  20. const localeDir = `${this.base}/${this.lang}`;
  21. let files = await fs.readdir(localeDir);
  22. files = [this.defaultLocale].concat(files.filter(file => file !== this.defaultLocale));
  23. for (const file of files) {
  24. const ext = path.extname(file);
  25. const transformer = transformers[ext];
  26. if (transformer) {
  27. try {
  28. const res = await fs.readFile(`${localeDir}/${file}`, 'utf8');
  29. Object.assign(this.data, transformer(res));
  30. } catch (err) {
  31. if (err.code !== 'ENOENT') {
  32. throw err;
  33. }
  34. }
  35. }
  36. }
  37. Object.keys(this.data)
  38. .forEach(key => {
  39. this.desc[key] = this.desc[key] || this.data[key].description;
  40. });
  41. }
  42. getMessage(key, def) {
  43. const item = this.data[key];
  44. return item && item.message || def;
  45. }
  46. get(key) {
  47. return this.data[key];
  48. }
  49. dump(data, { extension }) {
  50. if (extension === '.json') {
  51. data = JSON.stringify(data, null, 2);
  52. } else if (extension === '.yml') {
  53. data = yaml.safeDump(data, { sortKeys: true });
  54. } else {
  55. throw 'Unknown extension name!';
  56. }
  57. return {
  58. path: `${this.lang}/messages${extension}`,
  59. data,
  60. };
  61. }
  62. }
  63. class Locales {
  64. constructor(options) {
  65. this.options = options;
  66. this.defaultLang = 'en';
  67. this.newLocaleItem = 'NEW_LOCALE_ITEM';
  68. this.base = options.base || '.';
  69. this.langs = [];
  70. this.locales = {};
  71. this.data = {};
  72. }
  73. async load() {
  74. const langs = await fs.readdir(this.base);
  75. this.langs = langs;
  76. await Promise.all(langs.map(async lang => {
  77. const locale = new Locale(lang, this.base);
  78. await locale.load();
  79. this.locales[lang] = locale;
  80. }));
  81. const defaultData = this.locales[this.defaultLang];
  82. Object.keys(defaultData.desc).forEach(key => {
  83. this.data[key] = {
  84. ...defaultData.data[key],
  85. touched: this.options.markUntouched ? false : defaultData.get(key).touched !== false,
  86. };
  87. });
  88. }
  89. getData(lang, options) {
  90. options = options || {};
  91. const data = {};
  92. const langData = this.locales[lang];
  93. const defaultData = options.useDefaultLang && lang != this.defaultLang && this.locales[this.defaultLang];
  94. Object.keys(this.data).forEach(key => {
  95. if (options.touchedOnly && !this.data[key].touched) return;
  96. data[key] = {
  97. description: this.data[key].description || this.newLocaleItem,
  98. message: langData.getMessage(key) || defaultData && defaultData.getMessage(key) || '',
  99. };
  100. if (options.markUntouched && !this.data[key].touched) data[key].touched = false;
  101. });
  102. return data;
  103. }
  104. dump(options) {
  105. options = { ...this.options, ...options };
  106. return this.langs.map(lang => {
  107. const data = this.getData(lang, options);
  108. const locale = this.locales[lang];
  109. return locale.dump(data, options);
  110. });
  111. }
  112. touch(key) {
  113. let item = this.data[key];
  114. if (!item) item = this.data[key] = {
  115. description: this.newLocaleItem,
  116. };
  117. item.touched = true;
  118. }
  119. }
  120. function extract(options) {
  121. const keys = new Set();
  122. const patterns = {
  123. default: ['\\b(?:i18n\\(\'|i18n-key=")(\\w+)[\'"]', 1],
  124. json: ['__MSG_(\\w+)__', 1],
  125. };
  126. const types = {
  127. '.js': 'default',
  128. '.json': 'json',
  129. '.html': 'default',
  130. '.vue': 'default',
  131. };
  132. const locales = new Locales(options);
  133. function extractFile(data, types) {
  134. if (!Array.isArray(types)) types = [types];
  135. data = String(data);
  136. types.forEach(function (type) {
  137. const patternData = patterns[type];
  138. const pattern = new RegExp(patternData[0], 'g');
  139. const groupId = patternData[1];
  140. let groups;
  141. while (groups = pattern.exec(data)) {
  142. keys.add(groups[groupId]);
  143. }
  144. });
  145. }
  146. function bufferContents(file, enc, cb) {
  147. if (file.isNull()) return cb();
  148. if (file.isStream()) return this.emit('error', new PluginError('VM-i18n', 'Stream is not supported.'));
  149. const extname = path.extname(file.path);
  150. const type = types[extname];
  151. if (type) extractFile(file.contents, type);
  152. cb();
  153. }
  154. function endStream(cb) {
  155. locales.load()
  156. .then(() => {
  157. keys.forEach(key => {
  158. locales.touch(key);
  159. });
  160. return locales.dump()
  161. .map(out => new Vinyl({
  162. path: out.path,
  163. contents: Buffer.from(out.data),
  164. }));
  165. })
  166. .then(files => {
  167. files.forEach(file => {
  168. this.push(file);
  169. });
  170. cb();
  171. })
  172. .catch(cb);
  173. }
  174. return through.obj(bufferContents, endStream);
  175. }
  176. function read(options) {
  177. const stream = extract(options);
  178. process.nextTick(() => stream.end());
  179. return stream;
  180. }
  181. module.exports = {
  182. extract,
  183. read,
  184. };