Initial commit
[yaffs-website] / node_modules / y18n / index.js
1 var fs = require('fs')
2 var path = require('path')
3 var util = require('util')
4
5 function Y18N (opts) {
6   // configurable options.
7   opts = opts || {}
8   this.directory = opts.directory || './locales'
9   this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true
10   this.locale = opts.locale || 'en'
11   this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true
12
13   // internal stuff.
14   this.cache = {}
15   this.writeQueue = []
16 }
17
18 Y18N.prototype.__ = function () {
19   var args = Array.prototype.slice.call(arguments)
20   var str = args.shift()
21   var cb = function () {} // start with noop.
22
23   if (typeof args[args.length - 1] === 'function') cb = args.pop()
24   cb = cb || function () {} // noop.
25
26   if (!this.cache[this.locale]) this._readLocaleFile()
27
28   // we've observed a new string, update the language file.
29   if (!this.cache[this.locale][str] && this.updateFiles) {
30     this.cache[this.locale][str] = str
31
32     // include the current directory and locale,
33     // since these values could change before the
34     // write is performed.
35     this._enqueueWrite([this.directory, this.locale, cb])
36   } else {
37     cb()
38   }
39
40   return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args))
41 }
42
43 Y18N.prototype._enqueueWrite = function (work) {
44   this.writeQueue.push(work)
45   if (this.writeQueue.length === 1) this._processWriteQueue()
46 }
47
48 Y18N.prototype._processWriteQueue = function () {
49   var _this = this
50   var work = this.writeQueue[0]
51
52   // destructure the enqueued work.
53   var directory = work[0]
54   var locale = work[1]
55   var cb = work[2]
56
57   var languageFile = this._resolveLocaleFile(directory, locale)
58   var serializedLocale = JSON.stringify(this.cache[locale], null, 2)
59
60   fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
61     _this.writeQueue.shift()
62     if (_this.writeQueue.length > 0) _this._processWriteQueue()
63     cb(err)
64   })
65 }
66
67 Y18N.prototype._readLocaleFile = function () {
68   var localeLookup = {}
69   var languageFile = this._resolveLocaleFile(this.directory, this.locale)
70
71   try {
72     localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8'))
73   } catch (err) {
74     if (err instanceof SyntaxError) {
75       err.message = 'syntax error in ' + languageFile
76     }
77
78     if (err.code === 'ENOENT') localeLookup = {}
79     else throw err
80   }
81
82   this.cache[this.locale] = localeLookup
83 }
84
85 Y18N.prototype._resolveLocaleFile = function (directory, locale) {
86   var file = path.resolve(directory, './', locale + '.json')
87   if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
88     // attempt fallback to language only
89     var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json')
90     if (this._fileExistsSync(languageFile)) file = languageFile
91   }
92   return file
93 }
94
95 // this only exists because fs.existsSync() "will be deprecated"
96 // see https://nodejs.org/api/fs.html#fs_fs_existssync_path
97 Y18N.prototype._fileExistsSync = function (file) {
98   try {
99     return fs.statSync(file).isFile()
100   } catch (err) {
101     return false
102   }
103 }
104
105 Y18N.prototype.__n = function () {
106   var args = Array.prototype.slice.call(arguments)
107   var singular = args.shift()
108   var plural = args.shift()
109   var quantity = args.shift()
110
111   var cb = function () {} // start with noop.
112   if (typeof args[args.length - 1] === 'function') cb = args.pop()
113
114   if (!this.cache[this.locale]) this._readLocaleFile()
115
116   var str = quantity === 1 ? singular : plural
117   if (this.cache[this.locale][singular]) {
118     str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other']
119   }
120
121   // we've observed a new string, update the language file.
122   if (!this.cache[this.locale][singular] && this.updateFiles) {
123     this.cache[this.locale][singular] = {
124       one: singular,
125       other: plural
126     }
127
128     // include the current directory and locale,
129     // since these values could change before the
130     // write is performed.
131     this._enqueueWrite([this.directory, this.locale, cb])
132   } else {
133     cb()
134   }
135
136   // if a %d placeholder is provided, add quantity
137   // to the arguments expanded by util.format.
138   var values = [str]
139   if (~str.indexOf('%d')) values.push(quantity)
140
141   return util.format.apply(util, values.concat(args))
142 }
143
144 Y18N.prototype.setLocale = function (locale) {
145   this.locale = locale
146 }
147
148 Y18N.prototype.getLocale = function () {
149   return this.locale
150 }
151
152 Y18N.prototype.updateLocale = function (obj) {
153   if (!this.cache[this.locale]) this._readLocaleFile()
154
155   for (var key in obj) {
156     this.cache[this.locale][key] = obj[key]
157   }
158 }
159
160 module.exports = function (opts) {
161   var y18n = new Y18N(opts)
162
163   // bind all functions to y18n, so that
164   // they can be used in isolation.
165   for (var key in y18n) {
166     if (typeof y18n[key] === 'function') {
167       y18n[key] = y18n[key].bind(y18n)
168     }
169   }
170
171   return y18n
172 }