i18n.js 47.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path");
var fs = require("fs");
var event_stream_1 = require("event-stream");
var File = require("vinyl");
var Is = require("is");
var xml2js = require("xml2js");
var glob = require("glob");
var https = require("https");
D
Dirk Baeumer 已提交
15
var gulp = require("gulp");
16 17
var util = require('gulp-util');
var iconv = require('iconv-lite');
18
var NUMBER_OF_CONCURRENT_DOWNLOADS = 4;
19 20 21 22 23 24 25
function log(message) {
    var rest = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        rest[_i - 1] = arguments[_i];
    }
    util.log.apply(util, [util.colors.green('[i18n]'), message].concat(rest));
}
D
Dirk Baeumer 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
exports.defaultLanguages = [
    { id: 'zh-tw', folderName: 'cht', transifexId: 'zh-hant' },
    { id: 'zh-cn', folderName: 'chs', transifexId: 'zh-hans' },
    { id: 'ja', folderName: 'jpn' },
    { id: 'ko', folderName: 'kor' },
    { id: 'de', folderName: 'deu' },
    { id: 'fr', folderName: 'fra' },
    { id: 'es', folderName: 'esn' },
    { id: 'ru', folderName: 'rus' },
    { id: 'it', folderName: 'ita' }
];
// languages requested by the community to non-stable builds
exports.extraLanguages = [
    { id: 'pt-br', folderName: 'ptb' },
    { id: 'hu', folderName: 'hun' },
    { id: 'tr', folderName: 'trk' }
];
exports.pseudoLanguage = { id: 'pseudo', folderName: 'pseudo', transifexId: 'pseudo' };
44 45 46 47 48 49 50 51
// non built-in extensions also that are transifex and need to be part of the language packs
var externalExtensionsWithTranslations = [
    "azure-account",
    "vscode-chrome-debug",
    "vscode-chrome-debug-core",
    "vscode-node-debug",
    "vscode-node-debug2"
];
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
var LocalizeInfo;
(function (LocalizeInfo) {
    function is(value) {
        var candidate = value;
        return Is.defined(candidate) && Is.string(candidate.key) && (Is.undef(candidate.comment) || (Is.array(candidate.comment) && candidate.comment.every(function (element) { return Is.string(element); })));
    }
    LocalizeInfo.is = is;
})(LocalizeInfo || (LocalizeInfo = {}));
var BundledFormat;
(function (BundledFormat) {
    function is(value) {
        if (Is.undef(value)) {
            return false;
        }
        var candidate = value;
        var length = Object.keys(value).length;
        return length === 3 && Is.defined(candidate.keys) && Is.defined(candidate.messages) && Is.defined(candidate.bundles);
    }
    BundledFormat.is = is;
})(BundledFormat || (BundledFormat = {}));
var PackageJsonFormat;
(function (PackageJsonFormat) {
    function is(value) {
        if (Is.undef(value) || !Is.object(value)) {
            return false;
        }
        return Object.keys(value).every(function (key) {
            var element = value[key];
            return Is.string(element) || (Is.object(element) && Is.defined(element.message) && Is.defined(element.comment));
        });
    }
    PackageJsonFormat.is = is;
})(PackageJsonFormat || (PackageJsonFormat = {}));
var ModuleJsonFormat;
(function (ModuleJsonFormat) {
    function is(value) {
        var candidate = value;
        return Is.defined(candidate)
            && Is.array(candidate.messages) && candidate.messages.every(function (message) { return Is.string(message); })
            && Is.array(candidate.keys) && candidate.keys.every(function (key) { return Is.string(key) || LocalizeInfo.is(key); });
    }
    ModuleJsonFormat.is = is;
})(ModuleJsonFormat || (ModuleJsonFormat = {}));
J
Joao 已提交
95
var Line = /** @class */ (function () {
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    function Line(indent) {
        if (indent === void 0) { indent = 0; }
        this.indent = indent;
        this.buffer = [];
        if (indent > 0) {
            this.buffer.push(new Array(indent + 1).join(' '));
        }
    }
    Line.prototype.append = function (value) {
        this.buffer.push(value);
        return this;
    };
    Line.prototype.toString = function () {
        return this.buffer.join('');
    };
    return Line;
}());
exports.Line = Line;
J
Joao 已提交
114
var TextModel = /** @class */ (function () {
115 116 117 118 119 120 121 122 123 124 125 126
    function TextModel(contents) {
        this._lines = contents.split(/\r\n|\r|\n/);
    }
    Object.defineProperty(TextModel.prototype, "lines", {
        get: function () {
            return this._lines;
        },
        enumerable: true,
        configurable: true
    });
    return TextModel;
}());
J
Joao 已提交
127
var XLF = /** @class */ (function () {
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    function XLF(project) {
        this.project = project;
        this.buffer = [];
        this.files = Object.create(null);
    }
    XLF.prototype.toString = function () {
        this.appendHeader();
        for (var file in this.files) {
            this.appendNewLine("<file original=\"" + file + "\" source-language=\"en\" datatype=\"plaintext\"><body>", 2);
            for (var _i = 0, _a = this.files[file]; _i < _a.length; _i++) {
                var item = _a[_i];
                this.addStringItem(item);
            }
            this.appendNewLine('</body></file>', 2);
        }
        this.appendFooter();
        return this.buffer.join('\r\n');
    };
    XLF.prototype.addFile = function (original, keys, messages) {
D
Dirk Baeumer 已提交
147 148 149
        if (keys.length !== messages.length) {
            throw new Error("Unmatching keys(" + keys.length + ") and messages(" + messages.length + ").");
        }
150
        this.files[original] = [];
D
Dirk Baeumer 已提交
151 152 153 154 155
        var existingKeys = new Set();
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var realKey = void 0;
            var comment = void 0;
156
            if (Is.string(key)) {
D
Dirk Baeumer 已提交
157 158
                realKey = key;
                comment = undefined;
159
            }
D
Dirk Baeumer 已提交
160 161 162 163
            else if (LocalizeInfo.is(key)) {
                realKey = key.key;
                if (key.comment && key.comment.length > 0) {
                    comment = key.comment.map(function (comment) { return encodeEntities(comment); }).join('\r\n');
164 165
                }
            }
D
Dirk Baeumer 已提交
166 167 168 169 170 171
            if (!realKey || existingKeys.has(realKey)) {
                continue;
            }
            existingKeys.add(realKey);
            var message = encodeEntities(messages[i]);
            this.files[original].push({ id: realKey, message: message, comment: comment });
172 173 174 175
        }
    };
    XLF.prototype.addStringItem = function (item) {
        if (!item.id || !item.message) {
D
Dirk Baeumer 已提交
176
            throw new Error("No item ID or value specified: " + JSON.stringify(item));
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        }
        this.appendNewLine("<trans-unit id=\"" + item.id + "\">", 4);
        this.appendNewLine("<source xml:lang=\"en\">" + item.message + "</source>", 6);
        if (item.comment) {
            this.appendNewLine("<note>" + item.comment + "</note>", 6);
        }
        this.appendNewLine('</trans-unit>', 4);
    };
    XLF.prototype.appendHeader = function () {
        this.appendNewLine('<?xml version="1.0" encoding="utf-8"?>', 0);
        this.appendNewLine('<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">', 0);
    };
    XLF.prototype.appendFooter = function () {
        this.appendNewLine('</xliff>', 0);
    };
    XLF.prototype.appendNewLine = function (content, indent) {
        var line = new Line(indent);
        line.append(content);
        this.buffer.push(line.toString());
    };
197 198 199 200 201 202
    XLF.parse = function (xlfString) {
        return new Promise(function (resolve, reject) {
            var parser = new xml2js.Parser();
            var files = [];
            parser.parseString(xlfString, function (err, result) {
                if (err) {
D
Dirk Baeumer 已提交
203
                    reject(new Error("XLF parsing error: Failed to parse XLIFF string. " + err));
204
                }
205 206
                var fileNodes = result['xliff']['file'];
                if (!fileNodes) {
D
Dirk Baeumer 已提交
207
                    reject(new Error("XLF parsing error: XLIFF file does not contain \"xliff\" or \"file\" node(s) required for parsing."));
208
                }
209 210 211
                fileNodes.forEach(function (file) {
                    var originalFilePath = file.$.original;
                    if (!originalFilePath) {
D
Dirk Baeumer 已提交
212
                        reject(new Error("XLF parsing error: XLIFF file node does not contain original attribute to determine the original location of the resource file."));
213
                    }
D
Dirk Baeumer 已提交
214
                    var language = file.$['target-language'];
215
                    if (!language) {
D
Dirk Baeumer 已提交
216
                        reject(new Error("XLF parsing error: XLIFF file node does not contain target-language attribute to determine translated language."));
217
                    }
218 219 220 221 222 223 224 225 226 227 228 229
                    var messages = {};
                    var transUnits = file.body[0]['trans-unit'];
                    transUnits.forEach(function (unit) {
                        var key = unit.$.id;
                        if (!unit.target) {
                            return; // No translation available
                        }
                        var val = unit.target.toString();
                        if (key && val) {
                            messages[key] = decodeEntities(val);
                        }
                        else {
D
Dirk Baeumer 已提交
230
                            reject(new Error("XLF parsing error: XLIFF file does not contain full localization data. ID or target translation for one of the trans-unit nodes is not present."));
231 232
                        }
                    });
D
Dirk Baeumer 已提交
233
                    files.push({ messages: messages, originalFilePath: originalFilePath, language: language.toLowerCase() });
234
                });
235
                resolve(files);
236 237
            });
        });
238 239 240
    };
    return XLF;
}());
241
exports.XLF = XLF;
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
var Limiter = /** @class */ (function () {
    function Limiter(maxDegreeOfParalellism) {
        this.maxDegreeOfParalellism = maxDegreeOfParalellism;
        this.outstandingPromises = [];
        this.runningPromises = 0;
    }
    Limiter.prototype.queue = function (factory) {
        var _this = this;
        return new Promise(function (c, e) {
            _this.outstandingPromises.push({ factory: factory, c: c, e: e });
            _this.consume();
        });
    };
    Limiter.prototype.consume = function () {
        var _this = this;
        while (this.outstandingPromises.length && this.runningPromises < this.maxDegreeOfParalellism) {
            var iLimitedTask = this.outstandingPromises.shift();
            this.runningPromises++;
            var promise = iLimitedTask.factory();
            promise.then(iLimitedTask.c).catch(iLimitedTask.e);
            promise.then(function () { return _this.consumed(); }).catch(function () { return _this.consumed(); });
        }
    };
    Limiter.prototype.consumed = function () {
        this.runningPromises--;
        this.consume();
    };
    return Limiter;
}());
exports.Limiter = Limiter;
D
Dirk Baeumer 已提交
272 273 274
function sortLanguages(languages) {
    return languages.sort(function (a, b) {
        return a.id < b.id ? -1 : (a.id > b.id ? 1 : 0);
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    });
}
function stripComments(content) {
    /**
    * First capturing group matches double quoted string
    * Second matches single quotes string
    * Third matches block comments
    * Fourth matches line comments
    */
    var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
    var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
        // Only one of m1, m2, m3, m4 matches
        if (m3) {
            // A block comment. Replace with nothing
            return '';
        }
        else if (m4) {
            // A line comment. If it ends in \r?\n then keep it.
            var length_1 = m4.length;
            if (length_1 > 2 && m4[length_1 - 1] === '\n') {
                return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
            }
            else {
                return '';
            }
        }
        else {
            // We match a string
            return match;
        }
    });
    return result;
}
function escapeCharacters(value) {
    var result = [];
    for (var i = 0; i < value.length; i++) {
        var ch = value.charAt(i);
        switch (ch) {
            case '\'':
                result.push('\\\'');
                break;
            case '"':
                result.push('\\"');
                break;
            case '\\':
                result.push('\\\\');
                break;
            case '\n':
                result.push('\\n');
                break;
            case '\r':
                result.push('\\r');
                break;
            case '\t':
                result.push('\\t');
                break;
            case '\b':
                result.push('\\b');
                break;
            case '\f':
                result.push('\\f');
                break;
            default:
                result.push(ch);
        }
    }
    return result.join('');
}
function processCoreBundleFormat(fileHeader, languages, json, emitter) {
    var keysSection = json.keys;
    var messageSection = json.messages;
    var bundleSection = json.bundles;
    var statistics = Object.create(null);
    var total = 0;
    var defaultMessages = Object.create(null);
    var modules = Object.keys(keysSection);
    modules.forEach(function (module) {
        var keys = keysSection[module];
        var messages = messageSection[module];
        if (!messages || keys.length !== messages.length) {
            emitter.emit('error', "Message for module " + module + " corrupted. Mismatch in number of keys and messages.");
            return;
        }
        var messageMap = Object.create(null);
        defaultMessages[module] = messageMap;
        keys.map(function (key, i) {
            total++;
D
Dirk Baeumer 已提交
362
            if (typeof key === 'string') {
363 364 365 366 367 368 369 370
                messageMap[key] = messages[i];
            }
            else {
                messageMap[key.key] = messages[i];
            }
        });
    });
    var languageDirectory = path.join(__dirname, '..', '..', 'i18n');
D
Dirk Baeumer 已提交
371 372
    var sortedLanguages = sortLanguages(languages);
    sortedLanguages.forEach(function (language) {
373
        if (process.env['VSCODE_BUILD_VERBOSE']) {
D
Dirk Baeumer 已提交
374
            log("Generating nls bundles for: " + language.id);
375
        }
D
Dirk Baeumer 已提交
376
        statistics[language.id] = 0;
377
        var localizedModules = Object.create(null);
D
Dirk Baeumer 已提交
378 379
        var languageFolderName = language.folderName || language.id;
        var cwd = path.join(languageDirectory, languageFolderName, 'src');
380 381 382 383 384 385 386 387 388 389 390 391 392
        modules.forEach(function (module) {
            var order = keysSection[module];
            var i18nFile = path.join(cwd, module) + '.i18n.json';
            var messages = null;
            if (fs.existsSync(i18nFile)) {
                var content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
                messages = JSON.parse(content);
            }
            else {
                if (process.env['VSCODE_BUILD_VERBOSE']) {
                    log("No localized messages found for module " + module + ". Using default messages.");
                }
                messages = defaultMessages[module];
D
Dirk Baeumer 已提交
393
                statistics[language.id] = statistics[language.id] + Object.keys(messages).length;
394 395 396 397
            }
            var localizedMessages = [];
            order.forEach(function (keyInfo) {
                var key = null;
D
Dirk Baeumer 已提交
398
                if (typeof keyInfo === 'string') {
399 400 401 402 403 404 405 406 407 408 409
                    key = keyInfo;
                }
                else {
                    key = keyInfo.key;
                }
                var message = messages[key];
                if (!message) {
                    if (process.env['VSCODE_BUILD_VERBOSE']) {
                        log("No localized message found for key " + key + " in module " + module + ". Using default message.");
                    }
                    message = defaultMessages[module][key];
D
Dirk Baeumer 已提交
410
                    statistics[language.id] = statistics[language.id] + 1;
411 412 413 414 415 416 417 418 419
                }
                localizedMessages.push(message);
            });
            localizedModules[module] = localizedMessages;
        });
        Object.keys(bundleSection).forEach(function (bundle) {
            var modules = bundleSection[bundle];
            var contents = [
                fileHeader,
D
Dirk Baeumer 已提交
420
                "define(\"" + bundle + ".nls." + language.id + "\", {"
421 422 423 424 425 426 427 428 429 430 431 432 433 434
            ];
            modules.forEach(function (module, index) {
                contents.push("\t\"" + module + "\": [");
                var messages = localizedModules[module];
                if (!messages) {
                    emitter.emit('error', "Didn't find messages for module " + module + ".");
                    return;
                }
                messages.forEach(function (message, index) {
                    contents.push("\t\t\"" + escapeCharacters(message) + (index < messages.length ? '",' : '"'));
                });
                contents.push(index < modules.length - 1 ? '\t],' : '\t]');
            });
            contents.push('});');
D
Dirk Baeumer 已提交
435
            emitter.queue(new File({ path: bundle + '.nls.' + language.id + '.js', contents: new Buffer(contents.join('\n'), 'utf-8') }));
436 437 438 439 440 441
        });
    });
    Object.keys(statistics).forEach(function (key) {
        var value = statistics[key];
        log(key + " has " + value + " untranslated strings.");
    });
D
Dirk Baeumer 已提交
442 443 444 445
    sortedLanguages.forEach(function (language) {
        var stats = statistics[language.id];
        if (Is.undef(stats)) {
            log("\tNo translations found for language " + language.id + ". Using default language instead.");
446 447 448 449 450 451 452 453 454 455 456 457 458
        }
    });
}
function processNlsFiles(opts) {
    return event_stream_1.through(function (file) {
        var fileName = path.basename(file.path);
        if (fileName === 'nls.metadata.json') {
            var json = null;
            if (file.isBuffer()) {
                json = JSON.parse(file.contents.toString('utf8'));
            }
            else {
                this.emit('error', "Failed to read component file: " + file.relative);
D
Dirk Baeumer 已提交
459
                return;
460 461 462 463 464
            }
            if (BundledFormat.is(json)) {
                processCoreBundleFormat(opts.fileHeader, opts.languages, json, this);
            }
        }
D
Dirk Baeumer 已提交
465
        this.queue(file);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    });
}
exports.processNlsFiles = processNlsFiles;
var editorProject = 'vscode-editor', workbenchProject = 'vscode-workbench', extensionsProject = 'vscode-extensions', setupProject = 'vscode-setup';
function getResource(sourceFile) {
    var resource;
    if (/^vs\/platform/.test(sourceFile)) {
        return { name: 'vs/platform', project: editorProject };
    }
    else if (/^vs\/editor\/contrib/.test(sourceFile)) {
        return { name: 'vs/editor/contrib', project: editorProject };
    }
    else if (/^vs\/editor/.test(sourceFile)) {
        return { name: 'vs/editor', project: editorProject };
    }
    else if (/^vs\/base/.test(sourceFile)) {
        return { name: 'vs/base', project: editorProject };
    }
    else if (/^vs\/code/.test(sourceFile)) {
        return { name: 'vs/code', project: workbenchProject };
    }
    else if (/^vs\/workbench\/parts/.test(sourceFile)) {
        resource = sourceFile.split('/', 4).join('/');
        return { name: resource, project: workbenchProject };
    }
    else if (/^vs\/workbench\/services/.test(sourceFile)) {
        resource = sourceFile.split('/', 4).join('/');
        return { name: resource, project: workbenchProject };
    }
    else if (/^vs\/workbench/.test(sourceFile)) {
        return { name: 'vs/workbench', project: workbenchProject };
    }
    throw new Error("Could not identify the XLF bundle for " + sourceFile);
}
exports.getResource = getResource;
D
Dirk Baeumer 已提交
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
function createXlfFilesForCoreBundle() {
    return event_stream_1.through(function (file) {
        var basename = path.basename(file.path);
        if (basename === 'nls.metadata.json') {
            if (file.isBuffer()) {
                var xlfs = Object.create(null);
                var json = JSON.parse(file.contents.toString('utf8'));
                for (var coreModule in json.keys) {
                    var projectResource = getResource(coreModule);
                    var resource = projectResource.name;
                    var project = projectResource.project;
                    var keys = json.keys[coreModule];
                    var messages = json.messages[coreModule];
                    if (keys.length !== messages.length) {
                        this.emit('error', "There is a mismatch between keys and messages in " + file.relative + " for module " + coreModule);
                        return;
                    }
                    else {
                        var xlf = xlfs[resource];
                        if (!xlf) {
                            xlf = new XLF(project);
                            xlfs[resource] = xlf;
                        }
                        xlf.addFile("src/" + coreModule, keys, messages);
                    }
                }
                for (var resource in xlfs) {
                    var xlf = xlfs[resource];
                    var filePath = xlf.project + "/" + resource.replace(/\//g, '_') + ".xlf";
                    var xlfFile = new File({
                        path: filePath,
                        contents: new Buffer(xlf.toString(), 'utf8')
                    });
                    this.queue(xlfFile);
                }
            }
            else {
                this.emit('error', new Error("File " + file.relative + " is not using a buffer content"));
                return;
            }
541
        }
D
Dirk Baeumer 已提交
542 543
        else {
            this.emit('error', new Error("File " + file.relative + " is not a core meta data file."));
544 545
            return;
        }
D
Dirk Baeumer 已提交
546 547 548 549 550 551 552 553 554 555 556 557
    });
}
exports.createXlfFilesForCoreBundle = createXlfFilesForCoreBundle;
function createXlfFilesForExtensions() {
    var counter = 0;
    var folderStreamEnded = false;
    var folderStreamEndEmitted = false;
    return event_stream_1.through(function (extensionFolder) {
        var folderStream = this;
        var stat = fs.statSync(extensionFolder.path);
        if (!stat.isDirectory()) {
            return;
558
        }
D
Dirk Baeumer 已提交
559 560
        var extensionName = path.basename(extensionFolder.path);
        if (extensionName === 'node_modules') {
561 562
            return;
        }
D
Dirk Baeumer 已提交
563 564 565 566 567 568 569
        counter++;
        var _xlf;
        function getXlf() {
            if (!_xlf) {
                _xlf = new XLF(extensionsProject);
            }
            return _xlf;
570
        }
D
Dirk Baeumer 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
        gulp.src(["./extensions/" + extensionName + "/package.nls.json", "./extensions/" + extensionName + "/**/nls.metadata.json"]).pipe(event_stream_1.through(function (file) {
            if (file.isBuffer()) {
                var buffer = file.contents;
                var basename = path.basename(file.path);
                if (basename === 'package.nls.json') {
                    var json_1 = JSON.parse(buffer.toString('utf8'));
                    var keys = Object.keys(json_1);
                    var messages = keys.map(function (key) {
                        var value = json_1[key];
                        if (Is.string(value)) {
                            return value;
                        }
                        else if (value) {
                            return value.message;
                        }
                        else {
                            return "Unknown message for key: " + key;
                        }
                    });
                    getXlf().addFile("extensions/" + extensionName + "/package", keys, messages);
                }
                else if (basename === 'nls.metadata.json') {
                    var json = JSON.parse(buffer.toString('utf8'));
                    var relPath = path.relative("./extensions/" + extensionName, path.dirname(file.path));
                    for (var file_1 in json) {
                        var fileContent = json[file_1];
                        getXlf().addFile("extensions/" + extensionName + "/" + relPath + "/" + file_1, fileContent.keys, fileContent.messages);
                    }
                }
                else {
                    this.emit('error', new Error(file.path + " is not a valid extension nls file"));
                    return;
                }
            }
        }, function () {
            if (_xlf) {
                var xlfFile = new File({
                    path: path.join(extensionsProject, extensionName + '.xlf'),
                    contents: new Buffer(_xlf.toString(), 'utf8')
                });
                folderStream.queue(xlfFile);
            }
            this.queue(null);
            counter--;
            if (counter === 0 && folderStreamEnded && !folderStreamEndEmitted) {
                folderStreamEndEmitted = true;
                folderStream.queue(null);
618
            }
D
Dirk Baeumer 已提交
619 620 621 622 623 624
        }));
    }, function () {
        folderStreamEnded = true;
        if (counter === 0) {
            folderStreamEndEmitted = true;
            this.queue(null);
625 626 627
        }
    });
}
D
Dirk Baeumer 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
exports.createXlfFilesForExtensions = createXlfFilesForExtensions;
function createXlfFilesForIsl() {
    return event_stream_1.through(function (file) {
        var projectName, resourceFile;
        if (path.basename(file.path) === 'Default.isl') {
            projectName = setupProject;
            resourceFile = 'setup_default.xlf';
        }
        else {
            projectName = workbenchProject;
            resourceFile = 'setup_messages.xlf';
        }
        var xlf = new XLF(projectName), keys = [], messages = [];
        var model = new TextModel(file.contents.toString());
        var inMessageSection = false;
        model.lines.forEach(function (line) {
            if (line.length === 0) {
                return;
            }
            var firstChar = line.charAt(0);
            switch (firstChar) {
                case ';':
                    // Comment line;
                    return;
                case '[':
                    inMessageSection = '[Messages]' === line || '[CustomMessages]' === line;
                    return;
            }
            if (!inMessageSection) {
                return;
            }
            var sections = line.split('=');
            if (sections.length !== 2) {
                throw new Error("Badly formatted message found: " + line);
            }
            else {
                var key = sections[0];
                var value = sections[1];
                if (key.length > 0 && value.length > 0) {
                    keys.push(key);
                    messages.push(value);
                }
            }
        });
        var originalPath = file.path.substring(file.cwd.length + 1, file.path.split('.')[0].length).replace(/\\/g, '/');
        xlf.addFile(originalPath, keys, messages);
        // Emit only upon all ISL files combined into single XLF instance
        var newFilePath = path.join(projectName, resourceFile);
        var xlfFile = new File({ path: newFilePath, contents: new Buffer(xlf.toString(), 'utf-8') });
        this.queue(xlfFile);
    });
}
exports.createXlfFilesForIsl = createXlfFilesForIsl;
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
function pushXlfFiles(apiHostname, username, password) {
    var tryGetPromises = [];
    var updateCreatePromises = [];
    return event_stream_1.through(function (file) {
        var project = path.dirname(file.relative);
        var fileName = path.basename(file.path);
        var slug = fileName.substr(0, fileName.length - '.xlf'.length);
        var credentials = username + ":" + password;
        // Check if resource already exists, if not, then create it.
        var promise = tryGetResource(project, slug, apiHostname, credentials);
        tryGetPromises.push(promise);
        promise.then(function (exists) {
            if (exists) {
                promise = updateResource(project, slug, file, apiHostname, credentials);
            }
            else {
                promise = createResource(project, slug, file, apiHostname, credentials);
            }
            updateCreatePromises.push(promise);
        });
    }, function () {
        var _this = this;
        // End the pipe only after all the communication with Transifex API happened
        Promise.all(tryGetPromises).then(function () {
            Promise.all(updateCreatePromises).then(function () {
D
Dirk Baeumer 已提交
706
                _this.queue(null);
707 708 709 710 711
            }).catch(function (reason) { throw new Error(reason); });
        }).catch(function (reason) { throw new Error(reason); });
    });
}
exports.pushXlfFiles = pushXlfFiles;
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
function getAllResources(project, apiHostname, username, password) {
    return new Promise(function (resolve, reject) {
        var credentials = username + ":" + password;
        var options = {
            hostname: apiHostname,
            path: "/api/2/project/" + project + "/resources",
            auth: credentials,
            method: 'GET'
        };
        var request = https.request(options, function (res) {
            var buffer = [];
            res.on('data', function (chunk) { return buffer.push(chunk); });
            res.on('end', function () {
                if (res.statusCode === 200) {
                    var json = JSON.parse(Buffer.concat(buffer).toString());
                    if (Array.isArray(json)) {
                        resolve(json.map(function (o) { return o.slug; }));
                        return;
                    }
                    reject("Unexpected data format. Response code: " + res.statusCode + ".");
                }
                else {
                    reject("No resources in " + project + " returned no data. Response code: " + res.statusCode + ".");
                }
            });
        });
        request.on('error', function (err) {
            reject("Failed to query resources in " + project + " with the following error: " + err + ". " + options.path);
        });
        request.end();
    });
}
function findObsoleteResources(apiHostname, username, password) {
    var resourcesByProject = Object.create(null);
    resourcesByProject[extensionsProject] = [].concat(externalExtensionsWithTranslations); // clone
    return event_stream_1.through(function (file) {
        var project = path.dirname(file.relative);
        var fileName = path.basename(file.path);
        var slug = fileName.substr(0, fileName.length - '.xlf'.length);
        var slugs = resourcesByProject[project];
        if (!slugs) {
            resourcesByProject[project] = slugs = [];
        }
        slugs.push(slug);
        this.push(file);
    }, function () {
        var _this = this;
        var promises = [];
        var _loop_1 = function (project) {
            promises.push(getAllResources(project, apiHostname, username, password).then(function (resources) {
                var expectedResources = resourcesByProject[project];
                var unusedResources = resources.filter(function (resource) { return resource && expectedResources.indexOf(resource) === -1; });
                if (unusedResources.length) {
                    console.log("[transifex] Obsolete resources in project '" + project + "': " + unusedResources.join(', '));
                }
            }));
        };
        for (var project in resourcesByProject) {
            _loop_1(project);
        }
        return Promise.all(promises).then(function (_) {
            _this.push(null);
        }).catch(function (reason) { throw new Error(reason); });
    });
}
exports.findObsoleteResources = findObsoleteResources;
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
function tryGetResource(project, slug, apiHostname, credentials) {
    return new Promise(function (resolve, reject) {
        var options = {
            hostname: apiHostname,
            path: "/api/2/project/" + project + "/resource/" + slug + "/?details",
            auth: credentials,
            method: 'GET'
        };
        var request = https.request(options, function (response) {
            if (response.statusCode === 404) {
                resolve(false);
            }
            else if (response.statusCode === 200) {
                resolve(true);
            }
            else {
                reject("Failed to query resource " + project + "/" + slug + ". Response: " + response.statusCode + " " + response.statusMessage);
            }
        });
        request.on('error', function (err) {
            reject("Failed to get " + project + "/" + slug + " on Transifex: " + err);
        });
        request.end();
    });
}
function createResource(project, slug, xlfFile, apiHostname, credentials) {
    return new Promise(function (resolve, reject) {
        var data = JSON.stringify({
            'content': xlfFile.contents.toString(),
            'name': slug,
            'slug': slug,
            'i18n_type': 'XLIFF'
        });
        var options = {
            hostname: apiHostname,
            path: "/api/2/project/" + project + "/resources",
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(data)
            },
            auth: credentials,
            method: 'POST'
        };
        var request = https.request(options, function (res) {
            if (res.statusCode === 201) {
                log("Resource " + project + "/" + slug + " successfully created on Transifex.");
            }
            else {
                reject("Something went wrong in the request creating " + slug + " in " + project + ". " + res.statusCode);
            }
        });
        request.on('error', function (err) {
            reject("Failed to create " + project + "/" + slug + " on Transifex: " + err);
        });
        request.write(data);
        request.end();
    });
}
/**
 * The following link provides information about how Transifex handles updates of a resource file:
 * https://dev.befoolish.co/tx-docs/public/projects/updating-content#what-happens-when-you-update-files
 */
function updateResource(project, slug, xlfFile, apiHostname, credentials) {
    return new Promise(function (resolve, reject) {
        var data = JSON.stringify({ content: xlfFile.contents.toString() });
        var options = {
            hostname: apiHostname,
            path: "/api/2/project/" + project + "/resource/" + slug + "/content",
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(data)
            },
            auth: credentials,
            method: 'PUT'
        };
        var request = https.request(options, function (res) {
            if (res.statusCode === 200) {
                res.setEncoding('utf8');
                var responseBuffer_1 = '';
                res.on('data', function (chunk) {
                    responseBuffer_1 += chunk;
                });
                res.on('end', function () {
                    var response = JSON.parse(responseBuffer_1);
                    log("Resource " + project + "/" + slug + " successfully updated on Transifex. Strings added: " + response.strings_added + ", updated: " + response.strings_added + ", deleted: " + response.strings_added);
                    resolve();
                });
            }
            else {
                reject("Something went wrong in the request updating " + slug + " in " + project + ". " + res.statusCode);
            }
        });
        request.on('error', function (err) {
            reject("Failed to update " + project + "/" + slug + " on Transifex: " + err);
        });
        request.write(data);
        request.end();
    });
}
D
Dirk Baeumer 已提交
877
// cache resources
878 879 880 881
var _coreAndExtensionResources;
function pullCoreAndExtensionsXlfFiles(apiHostname, username, password, language) {
    if (!_coreAndExtensionResources) {
        _coreAndExtensionResources = [];
D
Dirk Baeumer 已提交
882 883
        // editor and workbench
        var json = JSON.parse(fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'));
884 885
        _coreAndExtensionResources.push.apply(_coreAndExtensionResources, json.editor);
        _coreAndExtensionResources.push.apply(_coreAndExtensionResources, json.workbench);
D
Dirk Baeumer 已提交
886 887 888 889
        // extensions
        var extensionsToLocalize_1 = Object.create(null);
        glob.sync('./extensions/**/*.nls.json').forEach(function (extension) { return extensionsToLocalize_1[extension.split('/')[2]] = true; });
        glob.sync('./extensions/*/node_modules/vscode-nls').forEach(function (extension) { return extensionsToLocalize_1[extension.split('/')[2]] = true; });
890 891 892 893
        for (var _i = 0, externalExtensionsWithTranslations_1 = externalExtensionsWithTranslations; _i < externalExtensionsWithTranslations_1.length; _i++) {
            var extension = externalExtensionsWithTranslations_1[_i];
            extensionsToLocalize_1[extension] = true;
        }
D
Dirk Baeumer 已提交
894
        Object.keys(extensionsToLocalize_1).forEach(function (extension) {
895
            _coreAndExtensionResources.push({ name: extension, project: extensionsProject });
896 897
        });
    }
898
    return pullXlfFiles(apiHostname, username, password, language, _coreAndExtensionResources);
899
}
900
exports.pullCoreAndExtensionsXlfFiles = pullCoreAndExtensionsXlfFiles;
D
Dirk Baeumer 已提交
901
function pullSetupXlfFiles(apiHostname, username, password, language, includeDefault) {
902
    var setupResources = [{ name: 'setup_messages', project: workbenchProject }];
D
Dirk Baeumer 已提交
903
    if (includeDefault) {
904
        setupResources.push({ name: 'setup_default', project: setupProject });
905
    }
D
Dirk Baeumer 已提交
906 907 908 909
    return pullXlfFiles(apiHostname, username, password, language, setupResources);
}
exports.pullSetupXlfFiles = pullSetupXlfFiles;
function pullXlfFiles(apiHostname, username, password, language, resources) {
910
    var credentials = username + ":" + password;
D
Dirk Baeumer 已提交
911
    var expectedTranslationsCount = resources.length;
912 913 914 915 916 917 918 919 920
    var translationsRetrieved = 0, called = false;
    return event_stream_1.readable(function (count, callback) {
        // Mark end of stream when all resources were retrieved
        if (translationsRetrieved === expectedTranslationsCount) {
            return this.emit('end');
        }
        if (!called) {
            called = true;
            var stream_1 = this;
D
Dirk Baeumer 已提交
921 922 923
            resources.map(function (resource) {
                retrieveResource(language, resource, apiHostname, credentials).then(function (file) {
                    if (file) {
924
                        stream_1.emit('data', file);
D
Dirk Baeumer 已提交
925 926 927
                    }
                    translationsRetrieved++;
                }).catch(function (error) { throw new Error(error); });
928 929 930 931 932
            });
        }
        callback();
    });
}
933
var limiter = new Limiter(NUMBER_OF_CONCURRENT_DOWNLOADS);
934
function retrieveResource(language, resource, apiHostname, credentials) {
935
    return limiter.queue(function () { return new Promise(function (resolve, reject) {
936 937
        var slug = resource.name.replace(/\//g, '_');
        var project = resource.project;
D
Dirk Baeumer 已提交
938
        var transifexLanguageId = language.transifexId || language.id;
939 940
        var options = {
            hostname: apiHostname,
D
Dirk Baeumer 已提交
941
            path: "/api/2/project/" + project + "/resource/" + slug + "/translation/" + transifexLanguageId + "?file&mode=onlyreviewed",
942
            auth: credentials,
943
            port: 443,
944 945
            method: 'GET'
        };
946
        console.log('Fetching ' + options.path);
947 948 949 950 951
        var request = https.request(options, function (res) {
            var xlfBuffer = [];
            res.on('data', function (chunk) { return xlfBuffer.push(chunk); });
            res.on('end', function () {
                if (res.statusCode === 200) {
D
Dirk Baeumer 已提交
952 953 954 955 956 957 958 959
                    resolve(new File({ contents: Buffer.concat(xlfBuffer), path: project + "/" + slug + ".xlf" }));
                }
                else if (res.statusCode === 404) {
                    console.log(slug + " in " + project + " returned no data.");
                    resolve(null);
                }
                else {
                    reject(slug + " in " + project + " returned no data. Response code: " + res.statusCode + ".");
960 961 962 963
                }
            });
        });
        request.on('error', function (err) {
964
            reject("Failed to query resource " + slug + " with the following error: " + err + ". " + options.path);
965 966
        });
        request.end();
967
    }); });
968
}
D
Dirk Baeumer 已提交
969
function prepareI18nFiles() {
970 971 972 973 974 975 976
    var parsePromises = [];
    return event_stream_1.through(function (xlf) {
        var stream = this;
        var parsePromise = XLF.parse(xlf.contents.toString());
        parsePromises.push(parsePromise);
        parsePromise.then(function (resolvedFiles) {
            resolvedFiles.forEach(function (file) {
D
Dirk Baeumer 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
                var translatedFile = createI18nFile(file.originalFilePath, file.messages);
                stream.queue(translatedFile);
            });
        });
    }, function () {
        var _this = this;
        Promise.all(parsePromises)
            .then(function () { _this.queue(null); })
            .catch(function (reason) { throw new Error(reason); });
    });
}
exports.prepareI18nFiles = prepareI18nFiles;
function createI18nFile(originalFilePath, messages) {
    var result = Object.create(null);
    result[''] = [
        '--------------------------------------------------------------------------------------------',
        'Copyright (c) Microsoft Corporation. All rights reserved.',
        'Licensed under the MIT License. See License.txt in the project root for license information.',
        '--------------------------------------------------------------------------------------------',
        'Do not edit this file. It is machine generated.'
    ];
    for (var _i = 0, _a = Object.keys(messages); _i < _a.length; _i++) {
        var key = _a[_i];
        result[key] = messages[key];
    }
    var content = JSON.stringify(result, null, '\t').replace(/\r\n/g, '\n');
    return new File({
        path: path.join(originalFilePath + '.i18n.json'),
        contents: new Buffer(content, 'utf8')
    });
}
var i18nPackVersion = "1.0.0";
function pullI18nPackFiles(apiHostname, username, password, language) {
1010
    return pullCoreAndExtensionsXlfFiles(apiHostname, username, password, language).pipe(prepareI18nPackFiles());
D
Dirk Baeumer 已提交
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
}
exports.pullI18nPackFiles = pullI18nPackFiles;
function prepareI18nPackFiles() {
    var parsePromises = [];
    var mainPack = { version: i18nPackVersion, contents: {} };
    var extensionsPacks = {};
    return event_stream_1.through(function (xlf) {
        var stream = this;
        var parsePromise = XLF.parse(xlf.contents.toString());
        parsePromises.push(parsePromise);
        parsePromise.then(function (resolvedFiles) {
            resolvedFiles.forEach(function (file) {
                var path = file.originalFilePath;
                var firstSlash = path.indexOf('/');
                var firstSegment = path.substr(0, firstSlash);
                if (firstSegment === 'src') {
                    mainPack.contents[path.substr(firstSlash + 1)] = file.messages;
                }
                else if (firstSegment === 'extensions') {
                    var secondSlash = path.indexOf('/', firstSlash + 1);
                    var secondSegment = path.substring(firstSlash + 1, secondSlash);
                    if (secondSegment) {
                        var extPack = extensionsPacks[secondSegment];
                        if (!extPack) {
                            extPack = extensionsPacks[secondSegment] = { version: i18nPackVersion, contents: {} };
                        }
                        extPack.contents[path.substr(secondSlash + 1)] = file.messages;
                    }
                    else {
                        console.log('Unknown second segment ' + path);
1041 1042 1043
                    }
                }
                else {
D
Dirk Baeumer 已提交
1044
                    console.log('Unknown first segment ' + path);
1045 1046 1047 1048 1049 1050
                }
            });
        });
    }, function () {
        var _this = this;
        Promise.all(parsePromises)
D
Dirk Baeumer 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059
            .then(function () {
            var translatedMainFile = createI18nFile('./main', mainPack);
            _this.queue(translatedMainFile);
            for (var extension in extensionsPacks) {
                var translatedExtFile = createI18nFile("./extensions/" + extension, extensionsPacks[extension]);
                _this.queue(translatedExtFile);
            }
            _this.queue(null);
        })
1060 1061 1062
            .catch(function (reason) { throw new Error(reason); });
    });
}
D
Dirk Baeumer 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
exports.prepareI18nPackFiles = prepareI18nPackFiles;
function prepareIslFiles(language, innoSetupConfig) {
    var parsePromises = [];
    return event_stream_1.through(function (xlf) {
        var stream = this;
        var parsePromise = XLF.parse(xlf.contents.toString());
        parsePromises.push(parsePromise);
        parsePromise.then(function (resolvedFiles) {
            resolvedFiles.forEach(function (file) {
                if (path.basename(file.originalFilePath) === 'Default' && !innoSetupConfig.defaultInfo) {
                    return;
                }
                var translatedFile = createIslFile(file.originalFilePath, file.messages, language, innoSetupConfig);
                stream.queue(translatedFile);
            });
        });
    }, function () {
        var _this = this;
        Promise.all(parsePromises)
            .then(function () { _this.queue(null); })
            .catch(function (reason) { throw new Error(reason); });
1084 1085
    });
}
D
Dirk Baeumer 已提交
1086 1087
exports.prepareIslFiles = prepareIslFiles;
function createIslFile(originalFilePath, messages, language, innoSetup) {
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
    var content = [];
    var originalContent;
    if (path.basename(originalFilePath) === 'Default') {
        originalContent = new TextModel(fs.readFileSync(originalFilePath + '.isl', 'utf8'));
    }
    else {
        originalContent = new TextModel(fs.readFileSync(originalFilePath + '.en.isl', 'utf8'));
    }
    originalContent.lines.forEach(function (line) {
        if (line.length > 0) {
            var firstChar = line.charAt(0);
            if (firstChar === '[' || firstChar === ';') {
                if (line === '; *** Inno Setup version 5.5.3+ English messages ***') {
D
Dirk Baeumer 已提交
1101
                    content.push("; *** Inno Setup version 5.5.3+ " + innoSetup.defaultInfo.name + " messages ***");
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
                }
                else {
                    content.push(line);
                }
            }
            else {
                var sections = line.split('=');
                var key = sections[0];
                var translated = line;
                if (key) {
                    if (key === 'LanguageName') {
D
Dirk Baeumer 已提交
1113
                        translated = key + "=" + innoSetup.defaultInfo.name;
1114 1115
                    }
                    else if (key === 'LanguageID') {
D
Dirk Baeumer 已提交
1116
                        translated = key + "=" + innoSetup.defaultInfo.id;
1117 1118
                    }
                    else if (key === 'LanguageCodePage') {
D
Dirk Baeumer 已提交
1119
                        translated = key + "=" + innoSetup.codePage.substr(2);
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
                    }
                    else {
                        var translatedMessage = messages[key];
                        if (translatedMessage) {
                            translated = key + "=" + translatedMessage;
                        }
                    }
                }
                content.push(translated);
            }
        }
    });
    var basename = path.basename(originalFilePath);
D
Dirk Baeumer 已提交
1133
    var filePath = basename + "." + language.id + ".isl";
1134 1135
    return new File({
        path: filePath,
D
Dirk Baeumer 已提交
1136
        contents: iconv.encode(new Buffer(content.join('\r\n'), 'utf8'), innoSetup.codePage)
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    });
}
function encodeEntities(value) {
    var result = [];
    for (var i = 0; i < value.length; i++) {
        var ch = value[i];
        switch (ch) {
            case '<':
                result.push('&lt;');
                break;
            case '>':
                result.push('&gt;');
                break;
            case '&':
                result.push('&amp;');
                break;
            default:
                result.push(ch);
        }
    }
    return result.join('');
}
function decodeEntities(value) {
    return value.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
}