i18n.js 5.0 KB

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