index.cjs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. 'use strict';
  2. var fs = require('fs');
  3. var util = require('util');
  4. var path = require('path');
  5. let shim;
  6. class Y18N {
  7. constructor(opts) {
  8. // configurable options.
  9. opts = opts || {};
  10. this.directory = opts.directory || './locales';
  11. this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true;
  12. this.locale = opts.locale || 'en';
  13. this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true;
  14. // internal stuff.
  15. this.cache = Object.create(null);
  16. this.writeQueue = [];
  17. }
  18. __(...args) {
  19. if (typeof arguments[0] !== 'string') {
  20. return this._taggedLiteral(arguments[0], ...arguments);
  21. }
  22. const str = args.shift();
  23. let cb = function () { }; // start with noop.
  24. if (typeof args[args.length - 1] === 'function')
  25. cb = args.pop();
  26. cb = cb || function () { }; // noop.
  27. if (!this.cache[this.locale])
  28. this._readLocaleFile();
  29. // we've observed a new string, update the language file.
  30. if (!this.cache[this.locale][str] && this.updateFiles) {
  31. this.cache[this.locale][str] = str;
  32. // include the current directory and locale,
  33. // since these values could change before the
  34. // write is performed.
  35. this._enqueueWrite({
  36. directory: this.directory,
  37. locale: this.locale,
  38. cb
  39. });
  40. }
  41. else {
  42. cb();
  43. }
  44. return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args));
  45. }
  46. __n() {
  47. const args = Array.prototype.slice.call(arguments);
  48. const singular = args.shift();
  49. const plural = args.shift();
  50. const quantity = args.shift();
  51. let cb = function () { }; // start with noop.
  52. if (typeof args[args.length - 1] === 'function')
  53. cb = args.pop();
  54. if (!this.cache[this.locale])
  55. this._readLocaleFile();
  56. let str = quantity === 1 ? singular : plural;
  57. if (this.cache[this.locale][singular]) {
  58. const entry = this.cache[this.locale][singular];
  59. str = entry[quantity === 1 ? 'one' : 'other'];
  60. }
  61. // we've observed a new string, update the language file.
  62. if (!this.cache[this.locale][singular] && this.updateFiles) {
  63. this.cache[this.locale][singular] = {
  64. one: singular,
  65. other: plural
  66. };
  67. // include the current directory and locale,
  68. // since these values could change before the
  69. // write is performed.
  70. this._enqueueWrite({
  71. directory: this.directory,
  72. locale: this.locale,
  73. cb
  74. });
  75. }
  76. else {
  77. cb();
  78. }
  79. // if a %d placeholder is provided, add quantity
  80. // to the arguments expanded by util.format.
  81. const values = [str];
  82. if (~str.indexOf('%d'))
  83. values.push(quantity);
  84. return shim.format.apply(shim.format, values.concat(args));
  85. }
  86. setLocale(locale) {
  87. this.locale = locale;
  88. }
  89. getLocale() {
  90. return this.locale;
  91. }
  92. updateLocale(obj) {
  93. if (!this.cache[this.locale])
  94. this._readLocaleFile();
  95. for (const key in obj) {
  96. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  97. this.cache[this.locale][key] = obj[key];
  98. }
  99. }
  100. }
  101. _taggedLiteral(parts, ...args) {
  102. let str = '';
  103. parts.forEach(function (part, i) {
  104. const arg = args[i + 1];
  105. str += part;
  106. if (typeof arg !== 'undefined') {
  107. str += '%s';
  108. }
  109. });
  110. return this.__.apply(this, [str].concat([].slice.call(args, 1)));
  111. }
  112. _enqueueWrite(work) {
  113. this.writeQueue.push(work);
  114. if (this.writeQueue.length === 1)
  115. this._processWriteQueue();
  116. }
  117. _processWriteQueue() {
  118. const _this = this;
  119. const work = this.writeQueue[0];
  120. // destructure the enqueued work.
  121. const directory = work.directory;
  122. const locale = work.locale;
  123. const cb = work.cb;
  124. const languageFile = this._resolveLocaleFile(directory, locale);
  125. const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
  126. shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
  127. _this.writeQueue.shift();
  128. if (_this.writeQueue.length > 0)
  129. _this._processWriteQueue();
  130. cb(err);
  131. });
  132. }
  133. _readLocaleFile() {
  134. let localeLookup = {};
  135. const languageFile = this._resolveLocaleFile(this.directory, this.locale);
  136. try {
  137. // When using a bundler such as webpack, readFileSync may not be defined:
  138. if (shim.fs.readFileSync) {
  139. localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8'));
  140. }
  141. }
  142. catch (err) {
  143. if (err instanceof SyntaxError) {
  144. err.message = 'syntax error in ' + languageFile;
  145. }
  146. if (err.code === 'ENOENT')
  147. localeLookup = {};
  148. else
  149. throw err;
  150. }
  151. this.cache[this.locale] = localeLookup;
  152. }
  153. _resolveLocaleFile(directory, locale) {
  154. let file = shim.resolve(directory, './', locale + '.json');
  155. if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
  156. // attempt fallback to language only
  157. const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json');
  158. if (this._fileExistsSync(languageFile))
  159. file = languageFile;
  160. }
  161. return file;
  162. }
  163. _fileExistsSync(file) {
  164. return shim.exists(file);
  165. }
  166. }
  167. function y18n$1(opts, _shim) {
  168. shim = _shim;
  169. const y18n = new Y18N(opts);
  170. return {
  171. __: y18n.__.bind(y18n),
  172. __n: y18n.__n.bind(y18n),
  173. setLocale: y18n.setLocale.bind(y18n),
  174. getLocale: y18n.getLocale.bind(y18n),
  175. updateLocale: y18n.updateLocale.bind(y18n),
  176. locale: y18n.locale
  177. };
  178. }
  179. var nodePlatformShim = {
  180. fs: {
  181. readFileSync: fs.readFileSync,
  182. writeFile: fs.writeFile
  183. },
  184. format: util.format,
  185. resolve: path.resolve,
  186. exists: (file) => {
  187. try {
  188. return fs.statSync(file).isFile();
  189. }
  190. catch (err) {
  191. return false;
  192. }
  193. }
  194. };
  195. const y18n = (opts) => {
  196. return y18n$1(opts, nodePlatformShim);
  197. };
  198. module.exports = y18n;