2018-09-27 18:49:41 +00:00
|
|
|
const { FluentResource } = require('fluent/compat');
|
2017-12-19 18:06:45 +00:00
|
|
|
const fs = require('fs');
|
2017-08-24 21:54:02 +00:00
|
|
|
|
2018-09-27 18:49:41 +00:00
|
|
|
function toJSON(resource) {
|
|
|
|
return JSON.stringify(Array.from(resource));
|
2017-12-19 18:06:45 +00:00
|
|
|
}
|
|
|
|
|
2017-08-24 21:54:02 +00:00
|
|
|
module.exports = function(source) {
|
2018-07-12 20:13:49 +00:00
|
|
|
const localeExp = /([^/]+)\/[^/]+\.ftl$/;
|
2017-08-24 21:54:02 +00:00
|
|
|
const result = localeExp.exec(this.resourcePath);
|
|
|
|
const locale = result && result[1];
|
|
|
|
if (!locale) {
|
|
|
|
throw new Error(`couldn't find locale in: ${this.resourcePath}`);
|
|
|
|
}
|
2017-12-19 18:06:45 +00:00
|
|
|
|
2018-09-27 18:49:41 +00:00
|
|
|
// Parse the current language's translation file.
|
|
|
|
const locResource = FluentResource.fromString(source);
|
|
|
|
let enResource;
|
|
|
|
|
|
|
|
// If the current language is not en-US, also parse en-US to provide a
|
|
|
|
// fallback for missing translations.
|
|
|
|
if (locale !== 'en-US') {
|
|
|
|
const en_ftl = fs.readFileSync(
|
|
|
|
require.resolve('../public/locales/en-US/send.ftl'),
|
|
|
|
'utf8'
|
|
|
|
);
|
|
|
|
enResource = FluentResource.fromString(en_ftl);
|
|
|
|
}
|
|
|
|
|
2017-08-24 21:54:02 +00:00
|
|
|
return `
|
|
|
|
module.exports = \`
|
|
|
|
if (typeof window === 'undefined') {
|
2018-08-03 17:48:00 +00:00
|
|
|
var fluent = require('fluent');
|
2017-08-24 21:54:02 +00:00
|
|
|
}
|
2018-03-02 21:40:29 +00:00
|
|
|
(function () {
|
2018-09-27 18:49:41 +00:00
|
|
|
let bundles = [
|
|
|
|
['${locale}', ${toJSON(locResource)}],
|
|
|
|
${enResource ? `['en-US', ${toJSON(enResource)}]` : ''}
|
|
|
|
].map(([locale, entries]) => {
|
|
|
|
let bundle = new fluent.FluentBundle(locale, {useIsolating: false});
|
|
|
|
bundle.addResource(new fluent.FluentResource(entries));
|
|
|
|
return bundle;
|
|
|
|
});
|
|
|
|
|
2018-03-02 21:40:29 +00:00
|
|
|
function translate(id, data) {
|
2018-09-27 18:49:41 +00:00
|
|
|
for (let bundle of bundles) {
|
|
|
|
if (bundle.hasMessage(id)) {
|
|
|
|
let message = bundle.getMessage(id);
|
|
|
|
return bundle.format(message, data);
|
|
|
|
}
|
2018-03-02 21:40:29 +00:00
|
|
|
}
|
2017-08-24 21:54:02 +00:00
|
|
|
}
|
2018-09-27 18:49:41 +00:00
|
|
|
|
2018-03-02 21:40:29 +00:00
|
|
|
if (typeof window === 'undefined') {
|
|
|
|
module.exports = translate;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
window.translate = translate;
|
|
|
|
}
|
|
|
|
})();
|
2017-08-24 21:54:02 +00:00
|
|
|
\``;
|
|
|
|
};
|