2 /* --------------------------------------------------------------------------------------------
3 * Copyright (c) Microsoft Corporation. All rights reserved.
4 * Licensed under the MIT License. See License.txt in the project root for license information.
5 * ------------------------------------------------------------------------------------------ */
6 Object.defineProperty(exports, "__esModule", { value: true });
7 exports.config = exports.loadMessageBundle = void 0;
8 var path = require("path");
9 var fs = require("fs");
10 var ral_1 = require("../common/ral");
11 var common_1 = require("../common/common");
12 var common_2 = require("../common/common");
13 Object.defineProperty(exports, "MessageFormat", { enumerable: true, get: function () { return common_2.MessageFormat; } });
14 Object.defineProperty(exports, "BundleFormat", { enumerable: true, get: function () { return common_2.BundleFormat; } });
15 var toString = Object.prototype.toString;
16 function isNumber(value) {
17 return toString.call(value) === '[object Number]';
19 function isString(value) {
20 return toString.call(value) === '[object String]';
22 function isBoolean(value) {
23 return value === true || value === false;
25 function readJsonFileSync(filename) {
26 return JSON.parse(fs.readFileSync(filename, 'utf8'));
30 function initializeSettings() {
31 options = { locale: undefined, language: undefined, languagePackSupport: false, cacheLanguageResolution: true, messageFormat: common_1.MessageFormat.bundle };
32 if (isString(process.env.VSCODE_NLS_CONFIG)) {
34 var vscodeOptions_1 = JSON.parse(process.env.VSCODE_NLS_CONFIG);
35 var language = void 0;
36 if (vscodeOptions_1.availableLanguages) {
37 var value = vscodeOptions_1.availableLanguages['*'];
38 if (isString(value)) {
42 if (isString(vscodeOptions_1.locale)) {
43 options.locale = vscodeOptions_1.locale.toLowerCase();
45 if (language === undefined) {
46 options.language = options.locale;
48 else if (language !== 'en') {
49 options.language = language;
51 if (isBoolean(vscodeOptions_1._languagePackSupport)) {
52 options.languagePackSupport = vscodeOptions_1._languagePackSupport;
54 if (isString(vscodeOptions_1._cacheRoot)) {
55 options.cacheRoot = vscodeOptions_1._cacheRoot;
57 if (isString(vscodeOptions_1._languagePackId)) {
58 options.languagePackId = vscodeOptions_1._languagePackId;
60 if (isString(vscodeOptions_1._translationsConfigFile)) {
61 options.translationsConfigFile = vscodeOptions_1._translationsConfigFile;
63 options.translationsConfig = readJsonFileSync(options.translationsConfigFile);
66 // We can't read the translation config file. Mark the cache as corrupted.
67 if (vscodeOptions_1._corruptedFile) {
68 var dirname = path.dirname(vscodeOptions_1._corruptedFile);
69 fs.exists(dirname, function (exists) {
71 fs.writeFile(vscodeOptions_1._corruptedFile, 'corrupted', 'utf8', function (err) {
84 common_1.setPseudo(options.locale === 'pseudo');
85 resolvedBundles = Object.create(null);
88 function supportsLanguagePack() {
89 return options.languagePackSupport === true && options.cacheRoot !== undefined && options.languagePackId !== undefined && options.translationsConfigFile !== undefined
90 && options.translationsConfig !== undefined;
92 function createScopedLocalizeFunction(messages) {
93 return function (key, message) {
95 for (var _i = 2; _i < arguments.length; _i++) {
96 args[_i - 2] = arguments[_i];
99 if (key >= messages.length) {
100 console.error("Broken localize call found. Index out of bounds. Stacktrace is\n: " + new Error('').stack);
103 return common_1.format(messages[key], args);
106 if (isString(message)) {
107 console.warn("Message " + message + " didn't get externalized correctly.");
108 return common_1.format(message, args);
111 console.error("Broken localize call found. Stacktrace is\n: " + new Error('').stack);
116 function resolveLanguage(file) {
117 var resolvedLanguage;
118 if (options.cacheLanguageResolution && resolvedLanguage) {
119 resolvedLanguage = resolvedLanguage;
122 if (common_1.isPseudo || !options.language) {
123 resolvedLanguage = '.nls.json';
126 var locale = options.language;
128 var candidate = '.nls.' + locale + '.json';
129 if (fs.existsSync(file + candidate)) {
130 resolvedLanguage = candidate;
134 var index = locale.lastIndexOf('-');
136 locale = locale.substring(0, index);
139 resolvedLanguage = '.nls.json';
145 if (options.cacheLanguageResolution) {
146 resolvedLanguage = resolvedLanguage;
149 return file + resolvedLanguage;
151 function findInTheBoxBundle(root) {
152 var language = options.language;
154 var candidate = path.join(root, "nls.bundle." + language + ".json");
155 if (fs.existsSync(candidate)) {
159 var index = language.lastIndexOf('-');
161 language = language.substring(0, index);
164 language = undefined;
168 // Test if we can reslove the default bundle.
169 if (language === undefined) {
170 var candidate = path.join(root, 'nls.bundle.json');
171 if (fs.existsSync(candidate)) {
177 function mkdir(directory) {
179 fs.mkdirSync(directory);
182 if (err.code === 'EEXIST') {
185 else if (err.code === 'ENOENT') {
186 var parent = path.dirname(directory);
187 if (parent !== directory) {
189 fs.mkdirSync(directory);
197 function createDefaultNlsBundle(folder) {
198 var metaData = readJsonFileSync(path.join(folder, 'nls.metadata.json'));
199 var result = Object.create(null);
200 for (var module_1 in metaData) {
201 var entry = metaData[module_1];
202 result[module_1] = entry.messages;
206 function createNLSBundle(header, metaDataPath) {
207 var languagePackLocation = options.translationsConfig[header.id];
208 if (!languagePackLocation) {
211 var languagePack = readJsonFileSync(languagePackLocation).contents;
212 var metaData = readJsonFileSync(path.join(metaDataPath, 'nls.metadata.json'));
213 var result = Object.create(null);
214 for (var module_2 in metaData) {
215 var entry = metaData[module_2];
216 var translations = languagePack[header.outDir + "/" + module_2];
218 var resultMessages = [];
219 for (var i = 0; i < entry.keys.length; i++) {
220 var messageKey = entry.keys[i];
221 var key = isString(messageKey) ? messageKey : messageKey.key;
222 var translatedMessage = translations[key];
223 if (translatedMessage === undefined) {
224 translatedMessage = entry.messages[i];
226 resultMessages.push(translatedMessage);
228 result[module_2] = resultMessages;
231 result[module_2] = entry.messages;
236 function touch(file) {
238 fs.utimes(file, d, d, function () {
239 // Do nothing. Ignore
242 function cacheBundle(key, bundle) {
243 resolvedBundles[key] = bundle;
246 function loadNlsBundleOrCreateFromI18n(header, bundlePath) {
248 var bundle = path.join(options.cacheRoot, header.id + "-" + header.hash + ".json");
249 var useMemoryOnly = false;
250 var writeBundle = false;
252 result = JSON.parse(fs.readFileSync(bundle, { encoding: 'utf8', flag: 'r' }));
257 if (err.code === 'ENOENT') {
260 else if (err instanceof SyntaxError) {
261 // We have a syntax error. So no valid JSON. Use
262 console.log("Syntax error parsing message bundle: " + err.message + ".");
263 fs.unlink(bundle, function (err) {
265 console.error("Deleting corrupted bundle " + bundle + " failed.");
268 useMemoryOnly = true;
274 result = createNLSBundle(header, bundlePath);
275 if (!result || useMemoryOnly) {
280 fs.writeFileSync(bundle, JSON.stringify(result), { encoding: 'utf8', flag: 'wx' });
283 if (err.code === 'EEXIST') {
291 function loadDefaultNlsBundle(bundlePath) {
293 return createDefaultNlsBundle(bundlePath);
296 console.log("Generating default bundle from meta data failed.", err);
300 function loadNlsBundle(header, bundlePath) {
302 // Core decided to use a language pack. Do the same in the extension
303 if (supportsLanguagePack()) {
305 result = loadNlsBundleOrCreateFromI18n(header, bundlePath);
308 console.log("Load or create bundle failed ", err);
312 // No language pack found, but core is running in language pack mode
313 // Don't try to use old in the box bundles since the might be stale
314 // Fall right back to the default bundle.
315 if (options.languagePackSupport) {
316 return loadDefaultNlsBundle(bundlePath);
318 var candidate = findInTheBoxBundle(bundlePath);
321 return readJsonFileSync(candidate);
324 console.log("Loading in the box message bundle failed.", err);
327 result = loadDefaultNlsBundle(bundlePath);
331 function tryFindMetaDataHeaderFile(file) {
333 var dirname = path.dirname(file);
335 result = path.join(dirname, 'nls.metadata.header.json');
336 if (fs.existsSync(result)) {
339 var parent = path.dirname(dirname);
340 if (parent === dirname) {
350 function loadMessageBundle(file) {
352 // No file. We are in dev mode. Return the default
353 // localize function.
354 return common_1.localize;
356 // Remove extension since we load json files.
357 var ext = path.extname(file);
359 file = file.substr(0, file.length - ext.length);
361 if (options.messageFormat === common_1.MessageFormat.both || options.messageFormat === common_1.MessageFormat.bundle) {
362 var headerFile = tryFindMetaDataHeaderFile(file);
364 var bundlePath = path.dirname(headerFile);
365 var bundle = resolvedBundles[bundlePath];
366 if (bundle === undefined) {
368 var header = JSON.parse(fs.readFileSync(headerFile, 'utf8'));
370 var nlsBundle = loadNlsBundle(header, bundlePath);
371 bundle = cacheBundle(bundlePath, nlsBundle ? { header: header, nlsBundle: nlsBundle } : null);
374 console.error('Failed to load nls bundle', err);
375 bundle = cacheBundle(bundlePath, null);
379 console.error('Failed to read header file', err);
380 bundle = cacheBundle(bundlePath, null);
384 var module_3 = file.substr(bundlePath.length + 1).replace(/\\/g, '/');
385 var messages = bundle.nlsBundle[module_3];
386 if (messages === undefined) {
387 console.error("Messages for file " + file + " not found. See console for details.");
389 return 'Messages not found.';
392 return createScopedLocalizeFunction(messages);
396 if (options.messageFormat === common_1.MessageFormat.both || options.messageFormat === common_1.MessageFormat.file) {
397 // Try to load a single file bundle
399 var json = readJsonFileSync(resolveLanguage(file));
400 if (Array.isArray(json)) {
401 return createScopedLocalizeFunction(json);
404 if (common_1.isDefined(json.messages) && common_1.isDefined(json.keys)) {
405 return createScopedLocalizeFunction(json.messages);
408 console.error("String bundle '" + file + "' uses an unsupported format.");
410 return 'File bundle has unsupported format. See console for details';
416 if (err.code !== 'ENOENT') {
417 console.error('Failed to load single file bundle', err);
421 console.error("Failed to load message bundle for file " + file);
423 return 'Failed to load message bundle. See console for details.';
426 exports.loadMessageBundle = loadMessageBundle;
427 function config(opts) {
429 if (isString(opts.locale)) {
430 options.locale = opts.locale.toLowerCase();
431 options.language = options.locale;
432 resolvedBundles = Object.create(null);
434 if (opts.messageFormat !== undefined) {
435 options.messageFormat = opts.messageFormat;
437 if (opts.bundleFormat === common_1.BundleFormat.standalone && options.languagePackSupport === true) {
438 options.languagePackSupport = false;
441 common_1.setPseudo(options.locale === 'pseudo');
442 return loadMessageBundle;
444 exports.config = config;
445 ral_1.default.install(Object.freeze({
446 loadMessageBundle: loadMessageBundle,
449 //# sourceMappingURL=main.js.map