i18n.js 5.3 KB

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