mirror of
https://github.com/microsoft/vscode.git
synced 2025-12-24 04:09:28 +00:00
👷 update build files
This commit is contained in:
@@ -1,452 +1,451 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
var path = require("path");
|
||||||
var path = require("path");
|
var vm = require("vm");
|
||||||
var vm = require("vm");
|
/**
|
||||||
/**
|
* Bundle `entryPoints` given config `config`.
|
||||||
* Bundle `entryPoints` given config `config`.
|
*/
|
||||||
*/
|
function bundle(entryPoints, config, callback) {
|
||||||
function bundle(entryPoints, config, callback) {
|
var entryPointsMap = {};
|
||||||
var entryPointsMap = {};
|
entryPoints.forEach(function (module) {
|
||||||
entryPoints.forEach(function (module) {
|
entryPointsMap[module.name] = module;
|
||||||
entryPointsMap[module.name] = module;
|
});
|
||||||
});
|
var allMentionedModulesMap = {};
|
||||||
var allMentionedModulesMap = {};
|
entryPoints.forEach(function (module) {
|
||||||
entryPoints.forEach(function (module) {
|
allMentionedModulesMap[module.name] = true;
|
||||||
allMentionedModulesMap[module.name] = true;
|
(module.include || []).forEach(function (includedModule) {
|
||||||
(module.include || []).forEach(function (includedModule) {
|
allMentionedModulesMap[includedModule] = true;
|
||||||
allMentionedModulesMap[includedModule] = true;
|
});
|
||||||
});
|
(module.exclude || []).forEach(function (excludedModule) {
|
||||||
(module.exclude || []).forEach(function (excludedModule) {
|
allMentionedModulesMap[excludedModule] = true;
|
||||||
allMentionedModulesMap[excludedModule] = true;
|
});
|
||||||
});
|
});
|
||||||
});
|
var code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
|
||||||
var code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
|
var r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
|
||||||
var r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
|
var loaderModule = { exports: {} };
|
||||||
var loaderModule = { exports: {} };
|
r.call({}, require, loaderModule, loaderModule.exports);
|
||||||
r.call({}, require, loaderModule, loaderModule.exports);
|
var loader = loaderModule.exports;
|
||||||
var loader = loaderModule.exports;
|
config.isBuild = true;
|
||||||
config.isBuild = true;
|
loader.config(config);
|
||||||
loader.config(config);
|
loader(['require'], function (localRequire) {
|
||||||
loader(['require'], function (localRequire) {
|
var resolvePath = function (path) {
|
||||||
var resolvePath = function (path) {
|
var r = localRequire.toUrl(path);
|
||||||
var r = localRequire.toUrl(path);
|
if (!/\.js/.test(r)) {
|
||||||
if (!/\.js/.test(r)) {
|
return r + '.js';
|
||||||
return r + '.js';
|
}
|
||||||
}
|
return r;
|
||||||
return r;
|
};
|
||||||
};
|
for (var moduleId in entryPointsMap) {
|
||||||
for (var moduleId in entryPointsMap) {
|
var entryPoint = entryPointsMap[moduleId];
|
||||||
var entryPoint = entryPointsMap[moduleId];
|
if (entryPoint.append) {
|
||||||
if (entryPoint.append) {
|
entryPoint.append = entryPoint.append.map(resolvePath);
|
||||||
entryPoint.append = entryPoint.append.map(resolvePath);
|
}
|
||||||
}
|
if (entryPoint.prepend) {
|
||||||
if (entryPoint.prepend) {
|
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
|
||||||
entryPoint.prepend = entryPoint.prepend.map(resolvePath);
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
loader(Object.keys(allMentionedModulesMap), function () {
|
||||||
loader(Object.keys(allMentionedModulesMap), function () {
|
var modules = loader.getBuildInfo();
|
||||||
var modules = loader.getBuildInfo();
|
var partialResult = emitEntryPoints(modules, entryPointsMap);
|
||||||
var partialResult = emitEntryPoints(modules, entryPointsMap);
|
var cssInlinedResources = loader('vs/css').getInlinedResources();
|
||||||
var cssInlinedResources = loader('vs/css').getInlinedResources();
|
callback(null, {
|
||||||
callback(null, {
|
files: partialResult.files,
|
||||||
files: partialResult.files,
|
cssInlinedResources: cssInlinedResources,
|
||||||
cssInlinedResources: cssInlinedResources,
|
bundleData: partialResult.bundleData
|
||||||
bundleData: partialResult.bundleData
|
});
|
||||||
});
|
}, function (err) { return callback(err, null); });
|
||||||
}, function (err) { return callback(err, null); });
|
}
|
||||||
}
|
exports.bundle = bundle;
|
||||||
exports.bundle = bundle;
|
function emitEntryPoints(modules, entryPoints) {
|
||||||
function emitEntryPoints(modules, entryPoints) {
|
var modulesMap = {};
|
||||||
var modulesMap = {};
|
modules.forEach(function (m) {
|
||||||
modules.forEach(function (m) {
|
modulesMap[m.id] = m;
|
||||||
modulesMap[m.id] = m;
|
});
|
||||||
});
|
var modulesGraph = {};
|
||||||
var modulesGraph = {};
|
modules.forEach(function (m) {
|
||||||
modules.forEach(function (m) {
|
modulesGraph[m.id] = m.dependencies;
|
||||||
modulesGraph[m.id] = m.dependencies;
|
});
|
||||||
});
|
var sortedModules = topologicalSort(modulesGraph);
|
||||||
var sortedModules = topologicalSort(modulesGraph);
|
var result = [];
|
||||||
var result = [];
|
var usedPlugins = {};
|
||||||
var usedPlugins = {};
|
var bundleData = {
|
||||||
var bundleData = {
|
graph: modulesGraph,
|
||||||
graph: modulesGraph,
|
bundles: {}
|
||||||
bundles: {}
|
};
|
||||||
};
|
Object.keys(entryPoints).forEach(function (moduleToBundle) {
|
||||||
Object.keys(entryPoints).forEach(function (moduleToBundle) {
|
var info = entryPoints[moduleToBundle];
|
||||||
var info = entryPoints[moduleToBundle];
|
var rootNodes = [moduleToBundle].concat(info.include || []);
|
||||||
var rootNodes = [moduleToBundle].concat(info.include || []);
|
var allDependencies = visit(rootNodes, modulesGraph);
|
||||||
var allDependencies = visit(rootNodes, modulesGraph);
|
var excludes = ['require', 'exports', 'module'].concat(info.exclude || []);
|
||||||
var excludes = ['require', 'exports', 'module'].concat(info.exclude || []);
|
excludes.forEach(function (excludeRoot) {
|
||||||
excludes.forEach(function (excludeRoot) {
|
var allExcludes = visit([excludeRoot], modulesGraph);
|
||||||
var allExcludes = visit([excludeRoot], modulesGraph);
|
Object.keys(allExcludes).forEach(function (exclude) {
|
||||||
Object.keys(allExcludes).forEach(function (exclude) {
|
delete allDependencies[exclude];
|
||||||
delete allDependencies[exclude];
|
});
|
||||||
});
|
});
|
||||||
});
|
var includedModules = sortedModules.filter(function (module) {
|
||||||
var includedModules = sortedModules.filter(function (module) {
|
return allDependencies[module];
|
||||||
return allDependencies[module];
|
});
|
||||||
});
|
bundleData.bundles[moduleToBundle] = includedModules;
|
||||||
bundleData.bundles[moduleToBundle] = includedModules;
|
var res = emitEntryPoint(modulesMap, modulesGraph, moduleToBundle, includedModules, info.prepend, info.append, info.dest);
|
||||||
var res = emitEntryPoint(modulesMap, modulesGraph, moduleToBundle, includedModules, info.prepend, info.append, info.dest);
|
result = result.concat(res.files);
|
||||||
result = result.concat(res.files);
|
for (var pluginName in res.usedPlugins) {
|
||||||
for (var pluginName in res.usedPlugins) {
|
usedPlugins[pluginName] = usedPlugins[pluginName] || res.usedPlugins[pluginName];
|
||||||
usedPlugins[pluginName] = usedPlugins[pluginName] || res.usedPlugins[pluginName];
|
}
|
||||||
}
|
});
|
||||||
});
|
Object.keys(usedPlugins).forEach(function (pluginName) {
|
||||||
Object.keys(usedPlugins).forEach(function (pluginName) {
|
var plugin = usedPlugins[pluginName];
|
||||||
var plugin = usedPlugins[pluginName];
|
if (typeof plugin.finishBuild === 'function') {
|
||||||
if (typeof plugin.finishBuild === 'function') {
|
var write = function (filename, contents) {
|
||||||
var write = function (filename, contents) {
|
result.push({
|
||||||
result.push({
|
dest: filename,
|
||||||
dest: filename,
|
sources: [{
|
||||||
sources: [{
|
path: null,
|
||||||
path: null,
|
contents: contents
|
||||||
contents: contents
|
}]
|
||||||
}]
|
});
|
||||||
});
|
};
|
||||||
};
|
plugin.finishBuild(write);
|
||||||
plugin.finishBuild(write);
|
}
|
||||||
}
|
});
|
||||||
});
|
return {
|
||||||
return {
|
files: extractStrings(removeDuplicateTSBoilerplate(result)),
|
||||||
files: extractStrings(removeDuplicateTSBoilerplate(result)),
|
bundleData: bundleData
|
||||||
bundleData: bundleData
|
};
|
||||||
};
|
}
|
||||||
}
|
function extractStrings(destFiles) {
|
||||||
function extractStrings(destFiles) {
|
var parseDefineCall = function (moduleMatch, depsMatch) {
|
||||||
var parseDefineCall = function (moduleMatch, depsMatch) {
|
var module = moduleMatch.replace(/^"|"$/g, '');
|
||||||
var module = moduleMatch.replace(/^"|"$/g, '');
|
var deps = depsMatch.split(',');
|
||||||
var deps = depsMatch.split(',');
|
deps = deps.map(function (dep) {
|
||||||
deps = deps.map(function (dep) {
|
dep = dep.trim();
|
||||||
dep = dep.trim();
|
dep = dep.replace(/^"|"$/g, '');
|
||||||
dep = dep.replace(/^"|"$/g, '');
|
dep = dep.replace(/^'|'$/g, '');
|
||||||
dep = dep.replace(/^'|'$/g, '');
|
var prefix = null;
|
||||||
var prefix = null;
|
var _path = null;
|
||||||
var _path = null;
|
var pieces = dep.split('!');
|
||||||
var pieces = dep.split('!');
|
if (pieces.length > 1) {
|
||||||
if (pieces.length > 1) {
|
prefix = pieces[0] + '!';
|
||||||
prefix = pieces[0] + '!';
|
_path = pieces[1];
|
||||||
_path = pieces[1];
|
}
|
||||||
}
|
else {
|
||||||
else {
|
prefix = '';
|
||||||
prefix = '';
|
_path = pieces[0];
|
||||||
_path = pieces[0];
|
}
|
||||||
}
|
if (/^\.\//.test(_path) || /^\.\.\//.test(_path)) {
|
||||||
if (/^\.\//.test(_path) || /^\.\.\//.test(_path)) {
|
var res = path.join(path.dirname(module), _path).replace(/\\/g, '/');
|
||||||
var res = path.join(path.dirname(module), _path).replace(/\\/g, '/');
|
return prefix + res;
|
||||||
return prefix + res;
|
}
|
||||||
}
|
return prefix + _path;
|
||||||
return prefix + _path;
|
});
|
||||||
});
|
return {
|
||||||
return {
|
module: module,
|
||||||
module: module,
|
deps: deps
|
||||||
deps: deps
|
};
|
||||||
};
|
};
|
||||||
};
|
destFiles.forEach(function (destFile, index) {
|
||||||
destFiles.forEach(function (destFile, index) {
|
if (!/\.js$/.test(destFile.dest)) {
|
||||||
if (!/\.js$/.test(destFile.dest)) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
if (/\.nls\.js$/.test(destFile.dest)) {
|
||||||
if (/\.nls\.js$/.test(destFile.dest)) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
// Do one pass to record the usage counts for each module id
|
||||||
// Do one pass to record the usage counts for each module id
|
var useCounts = {};
|
||||||
var useCounts = {};
|
destFile.sources.forEach(function (source) {
|
||||||
destFile.sources.forEach(function (source) {
|
var matches = source.contents.match(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/);
|
||||||
var matches = source.contents.match(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/);
|
if (!matches) {
|
||||||
if (!matches) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
var defineCall = parseDefineCall(matches[1], matches[2]);
|
||||||
var defineCall = parseDefineCall(matches[1], matches[2]);
|
useCounts[defineCall.module] = (useCounts[defineCall.module] || 0) + 1;
|
||||||
useCounts[defineCall.module] = (useCounts[defineCall.module] || 0) + 1;
|
defineCall.deps.forEach(function (dep) {
|
||||||
defineCall.deps.forEach(function (dep) {
|
useCounts[dep] = (useCounts[dep] || 0) + 1;
|
||||||
useCounts[dep] = (useCounts[dep] || 0) + 1;
|
});
|
||||||
});
|
});
|
||||||
});
|
var sortedByUseModules = Object.keys(useCounts);
|
||||||
var sortedByUseModules = Object.keys(useCounts);
|
sortedByUseModules.sort(function (a, b) {
|
||||||
sortedByUseModules.sort(function (a, b) {
|
return useCounts[b] - useCounts[a];
|
||||||
return useCounts[b] - useCounts[a];
|
});
|
||||||
});
|
var replacementMap = {};
|
||||||
var replacementMap = {};
|
sortedByUseModules.forEach(function (module, index) {
|
||||||
sortedByUseModules.forEach(function (module, index) {
|
replacementMap[module] = index;
|
||||||
replacementMap[module] = index;
|
});
|
||||||
});
|
destFile.sources.forEach(function (source) {
|
||||||
destFile.sources.forEach(function (source) {
|
source.contents = source.contents.replace(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/, function (_, moduleMatch, depsMatch) {
|
||||||
source.contents = source.contents.replace(/define\(("[^"]+"),\s*\[(((, )?("|')[^"']+("|'))+)\]/, function (_, moduleMatch, depsMatch) {
|
var defineCall = parseDefineCall(moduleMatch, depsMatch);
|
||||||
var defineCall = parseDefineCall(moduleMatch, depsMatch);
|
return "define(__m[" + replacementMap[defineCall.module] + "/*" + defineCall.module + "*/], __M([" + defineCall.deps.map(function (dep) { return replacementMap[dep] + '/*' + dep + '*/'; }).join(',') + "])";
|
||||||
return "define(__m[" + replacementMap[defineCall.module] + "/*" + defineCall.module + "*/], __M([" + defineCall.deps.map(function (dep) { return replacementMap[dep] + '/*' + dep + '*/'; }).join(',') + "])";
|
});
|
||||||
});
|
});
|
||||||
});
|
destFile.sources.unshift({
|
||||||
destFile.sources.unshift({
|
path: null,
|
||||||
path: null,
|
contents: [
|
||||||
contents: [
|
'(function() {',
|
||||||
'(function() {',
|
"var __m = " + JSON.stringify(sortedByUseModules) + ";",
|
||||||
"var __m = " + JSON.stringify(sortedByUseModules) + ";",
|
"var __M = function(deps) {",
|
||||||
"var __M = function(deps) {",
|
" var result = [];",
|
||||||
" var result = [];",
|
" for (var i = 0, len = deps.length; i < len; i++) {",
|
||||||
" for (var i = 0, len = deps.length; i < len; i++) {",
|
" result[i] = __m[deps[i]];",
|
||||||
" result[i] = __m[deps[i]];",
|
" }",
|
||||||
" }",
|
" return result;",
|
||||||
" return result;",
|
"};"
|
||||||
"};"
|
].join('\n')
|
||||||
].join('\n')
|
});
|
||||||
});
|
destFile.sources.push({
|
||||||
destFile.sources.push({
|
path: null,
|
||||||
path: null,
|
contents: '}).call(this);'
|
||||||
contents: '}).call(this);'
|
});
|
||||||
});
|
});
|
||||||
});
|
return destFiles;
|
||||||
return destFiles;
|
}
|
||||||
}
|
function removeDuplicateTSBoilerplate(destFiles) {
|
||||||
function removeDuplicateTSBoilerplate(destFiles) {
|
// Taken from typescript compiler => emitFiles
|
||||||
// Taken from typescript compiler => emitFiles
|
var BOILERPLATE = [
|
||||||
var BOILERPLATE = [
|
{ start: /^var __extends/, end: /^};$/ },
|
||||||
{ start: /^var __extends/, end: /^};$/ },
|
{ start: /^var __assign/, end: /^};$/ },
|
||||||
{ start: /^var __assign/, end: /^};$/ },
|
{ start: /^var __decorate/, end: /^};$/ },
|
||||||
{ start: /^var __decorate/, end: /^};$/ },
|
{ start: /^var __metadata/, end: /^};$/ },
|
||||||
{ start: /^var __metadata/, end: /^};$/ },
|
{ start: /^var __param/, end: /^};$/ },
|
||||||
{ start: /^var __param/, end: /^};$/ },
|
{ start: /^var __awaiter/, end: /^};$/ },
|
||||||
{ start: /^var __awaiter/, end: /^};$/ },
|
];
|
||||||
];
|
destFiles.forEach(function (destFile) {
|
||||||
destFiles.forEach(function (destFile) {
|
var SEEN_BOILERPLATE = [];
|
||||||
var SEEN_BOILERPLATE = [];
|
destFile.sources.forEach(function (source) {
|
||||||
destFile.sources.forEach(function (source) {
|
var lines = source.contents.split(/\r\n|\n|\r/);
|
||||||
var lines = source.contents.split(/\r\n|\n|\r/);
|
var newLines = [];
|
||||||
var newLines = [];
|
var IS_REMOVING_BOILERPLATE = false, END_BOILERPLATE;
|
||||||
var IS_REMOVING_BOILERPLATE = false, END_BOILERPLATE;
|
for (var i = 0; i < lines.length; i++) {
|
||||||
for (var i = 0; i < lines.length; i++) {
|
var line = lines[i];
|
||||||
var line = lines[i];
|
if (IS_REMOVING_BOILERPLATE) {
|
||||||
if (IS_REMOVING_BOILERPLATE) {
|
newLines.push('');
|
||||||
newLines.push('');
|
if (END_BOILERPLATE.test(line)) {
|
||||||
if (END_BOILERPLATE.test(line)) {
|
IS_REMOVING_BOILERPLATE = false;
|
||||||
IS_REMOVING_BOILERPLATE = false;
|
}
|
||||||
}
|
}
|
||||||
}
|
else {
|
||||||
else {
|
for (var j = 0; j < BOILERPLATE.length; j++) {
|
||||||
for (var j = 0; j < BOILERPLATE.length; j++) {
|
var boilerplate = BOILERPLATE[j];
|
||||||
var boilerplate = BOILERPLATE[j];
|
if (boilerplate.start.test(line)) {
|
||||||
if (boilerplate.start.test(line)) {
|
if (SEEN_BOILERPLATE[j]) {
|
||||||
if (SEEN_BOILERPLATE[j]) {
|
IS_REMOVING_BOILERPLATE = true;
|
||||||
IS_REMOVING_BOILERPLATE = true;
|
END_BOILERPLATE = boilerplate.end;
|
||||||
END_BOILERPLATE = boilerplate.end;
|
}
|
||||||
}
|
else {
|
||||||
else {
|
SEEN_BOILERPLATE[j] = true;
|
||||||
SEEN_BOILERPLATE[j] = true;
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
if (IS_REMOVING_BOILERPLATE) {
|
||||||
if (IS_REMOVING_BOILERPLATE) {
|
newLines.push('');
|
||||||
newLines.push('');
|
}
|
||||||
}
|
else {
|
||||||
else {
|
newLines.push(line);
|
||||||
newLines.push(line);
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
source.contents = newLines.join('\n');
|
||||||
source.contents = newLines.join('\n');
|
});
|
||||||
});
|
});
|
||||||
});
|
return destFiles;
|
||||||
return destFiles;
|
}
|
||||||
}
|
function emitEntryPoint(modulesMap, deps, entryPoint, includedModules, prepend, append, dest) {
|
||||||
function emitEntryPoint(modulesMap, deps, entryPoint, includedModules, prepend, append, dest) {
|
if (!dest) {
|
||||||
if (!dest) {
|
dest = entryPoint + '.js';
|
||||||
dest = entryPoint + '.js';
|
}
|
||||||
}
|
var mainResult = {
|
||||||
var mainResult = {
|
sources: [],
|
||||||
sources: [],
|
dest: dest
|
||||||
dest: dest
|
}, results = [mainResult];
|
||||||
}, results = [mainResult];
|
var usedPlugins = {};
|
||||||
var usedPlugins = {};
|
var getLoaderPlugin = function (pluginName) {
|
||||||
var getLoaderPlugin = function (pluginName) {
|
if (!usedPlugins[pluginName]) {
|
||||||
if (!usedPlugins[pluginName]) {
|
usedPlugins[pluginName] = modulesMap[pluginName].exports;
|
||||||
usedPlugins[pluginName] = modulesMap[pluginName].exports;
|
}
|
||||||
}
|
return usedPlugins[pluginName];
|
||||||
return usedPlugins[pluginName];
|
};
|
||||||
};
|
includedModules.forEach(function (c) {
|
||||||
includedModules.forEach(function (c) {
|
var bangIndex = c.indexOf('!');
|
||||||
var bangIndex = c.indexOf('!');
|
if (bangIndex >= 0) {
|
||||||
if (bangIndex >= 0) {
|
var pluginName = c.substr(0, bangIndex);
|
||||||
var pluginName = c.substr(0, bangIndex);
|
var plugin = getLoaderPlugin(pluginName);
|
||||||
var plugin = getLoaderPlugin(pluginName);
|
mainResult.sources.push(emitPlugin(entryPoint, plugin, pluginName, c.substr(bangIndex + 1)));
|
||||||
mainResult.sources.push(emitPlugin(entryPoint, plugin, pluginName, c.substr(bangIndex + 1)));
|
return;
|
||||||
return;
|
}
|
||||||
}
|
var module = modulesMap[c];
|
||||||
var module = modulesMap[c];
|
if (module.path === 'empty:') {
|
||||||
if (module.path === 'empty:') {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
var contents = readFileAndRemoveBOM(module.path);
|
||||||
var contents = readFileAndRemoveBOM(module.path);
|
if (module.shim) {
|
||||||
if (module.shim) {
|
mainResult.sources.push(emitShimmedModule(c, deps[c], module.shim, module.path, contents));
|
||||||
mainResult.sources.push(emitShimmedModule(c, deps[c], module.shim, module.path, contents));
|
}
|
||||||
}
|
else {
|
||||||
else {
|
mainResult.sources.push(emitNamedModule(c, deps[c], module.defineLocation, module.path, contents));
|
||||||
mainResult.sources.push(emitNamedModule(c, deps[c], module.defineLocation, module.path, contents));
|
}
|
||||||
}
|
});
|
||||||
});
|
Object.keys(usedPlugins).forEach(function (pluginName) {
|
||||||
Object.keys(usedPlugins).forEach(function (pluginName) {
|
var plugin = usedPlugins[pluginName];
|
||||||
var plugin = usedPlugins[pluginName];
|
if (typeof plugin.writeFile === 'function') {
|
||||||
if (typeof plugin.writeFile === 'function') {
|
var req = (function () {
|
||||||
var req = (function () {
|
throw new Error('no-no!');
|
||||||
throw new Error('no-no!');
|
});
|
||||||
});
|
req.toUrl = function (something) { return something; };
|
||||||
req.toUrl = function (something) { return something; };
|
var write = function (filename, contents) {
|
||||||
var write = function (filename, contents) {
|
results.push({
|
||||||
results.push({
|
dest: filename,
|
||||||
dest: filename,
|
sources: [{
|
||||||
sources: [{
|
path: null,
|
||||||
path: null,
|
contents: contents
|
||||||
contents: contents
|
}]
|
||||||
}]
|
});
|
||||||
});
|
};
|
||||||
};
|
plugin.writeFile(pluginName, entryPoint, req, write, {});
|
||||||
plugin.writeFile(pluginName, entryPoint, req, write, {});
|
}
|
||||||
}
|
});
|
||||||
});
|
var toIFile = function (path) {
|
||||||
var toIFile = function (path) {
|
var contents = readFileAndRemoveBOM(path);
|
||||||
var contents = readFileAndRemoveBOM(path);
|
return {
|
||||||
return {
|
path: path,
|
||||||
path: path,
|
contents: contents
|
||||||
contents: contents
|
};
|
||||||
};
|
};
|
||||||
};
|
var toPrepend = (prepend || []).map(toIFile);
|
||||||
var toPrepend = (prepend || []).map(toIFile);
|
var toAppend = (append || []).map(toIFile);
|
||||||
var toAppend = (append || []).map(toIFile);
|
mainResult.sources = toPrepend.concat(mainResult.sources).concat(toAppend);
|
||||||
mainResult.sources = toPrepend.concat(mainResult.sources).concat(toAppend);
|
return {
|
||||||
return {
|
files: results,
|
||||||
files: results,
|
usedPlugins: usedPlugins
|
||||||
usedPlugins: usedPlugins
|
};
|
||||||
};
|
}
|
||||||
}
|
function readFileAndRemoveBOM(path) {
|
||||||
function readFileAndRemoveBOM(path) {
|
var BOM_CHAR_CODE = 65279;
|
||||||
var BOM_CHAR_CODE = 65279;
|
var contents = fs.readFileSync(path, 'utf8');
|
||||||
var contents = fs.readFileSync(path, 'utf8');
|
// Remove BOM
|
||||||
// Remove BOM
|
if (contents.charCodeAt(0) === BOM_CHAR_CODE) {
|
||||||
if (contents.charCodeAt(0) === BOM_CHAR_CODE) {
|
contents = contents.substring(1);
|
||||||
contents = contents.substring(1);
|
}
|
||||||
}
|
return contents;
|
||||||
return contents;
|
}
|
||||||
}
|
function emitPlugin(entryPoint, plugin, pluginName, moduleName) {
|
||||||
function emitPlugin(entryPoint, plugin, pluginName, moduleName) {
|
var result = '';
|
||||||
var result = '';
|
if (typeof plugin.write === 'function') {
|
||||||
if (typeof plugin.write === 'function') {
|
var write = (function (what) {
|
||||||
var write = (function (what) {
|
result += what;
|
||||||
result += what;
|
});
|
||||||
});
|
write.getEntryPoint = function () {
|
||||||
write.getEntryPoint = function () {
|
return entryPoint;
|
||||||
return entryPoint;
|
};
|
||||||
};
|
write.asModule = function (moduleId, code) {
|
||||||
write.asModule = function (moduleId, code) {
|
code = code.replace(/^define\(/, 'define("' + moduleId + '",');
|
||||||
code = code.replace(/^define\(/, 'define("' + moduleId + '",');
|
result += code;
|
||||||
result += code;
|
};
|
||||||
};
|
plugin.write(pluginName, moduleName, write);
|
||||||
plugin.write(pluginName, moduleName, write);
|
}
|
||||||
}
|
return {
|
||||||
return {
|
path: null,
|
||||||
path: null,
|
contents: result
|
||||||
contents: result
|
};
|
||||||
};
|
}
|
||||||
}
|
function emitNamedModule(moduleId, myDeps, defineCallPosition, path, contents) {
|
||||||
function emitNamedModule(moduleId, myDeps, defineCallPosition, path, contents) {
|
// `defineCallPosition` is the position in code: |define()
|
||||||
// `defineCallPosition` is the position in code: |define()
|
var defineCallOffset = positionToOffset(contents, defineCallPosition.line, defineCallPosition.col);
|
||||||
var defineCallOffset = positionToOffset(contents, defineCallPosition.line, defineCallPosition.col);
|
// `parensOffset` is the position in code: define|()
|
||||||
// `parensOffset` is the position in code: define|()
|
var parensOffset = contents.indexOf('(', defineCallOffset);
|
||||||
var parensOffset = contents.indexOf('(', defineCallOffset);
|
var insertStr = '"' + moduleId + '", ';
|
||||||
var insertStr = '"' + moduleId + '", ';
|
return {
|
||||||
return {
|
path: path,
|
||||||
path: path,
|
contents: contents.substr(0, parensOffset + 1) + insertStr + contents.substr(parensOffset + 1)
|
||||||
contents: contents.substr(0, parensOffset + 1) + insertStr + contents.substr(parensOffset + 1)
|
};
|
||||||
};
|
}
|
||||||
}
|
function emitShimmedModule(moduleId, myDeps, factory, path, contents) {
|
||||||
function emitShimmedModule(moduleId, myDeps, factory, path, contents) {
|
var strDeps = (myDeps.length > 0 ? '"' + myDeps.join('", "') + '"' : '');
|
||||||
var strDeps = (myDeps.length > 0 ? '"' + myDeps.join('", "') + '"' : '');
|
var strDefine = 'define("' + moduleId + '", [' + strDeps + '], ' + factory + ');';
|
||||||
var strDefine = 'define("' + moduleId + '", [' + strDeps + '], ' + factory + ');';
|
return {
|
||||||
return {
|
path: path,
|
||||||
path: path,
|
contents: contents + '\n;\n' + strDefine
|
||||||
contents: contents + '\n;\n' + strDefine
|
};
|
||||||
};
|
}
|
||||||
}
|
/**
|
||||||
/**
|
* Convert a position (line:col) to (offset) in string `str`
|
||||||
* Convert a position (line:col) to (offset) in string `str`
|
*/
|
||||||
*/
|
function positionToOffset(str, desiredLine, desiredCol) {
|
||||||
function positionToOffset(str, desiredLine, desiredCol) {
|
if (desiredLine === 1) {
|
||||||
if (desiredLine === 1) {
|
return desiredCol - 1;
|
||||||
return desiredCol - 1;
|
}
|
||||||
}
|
var line = 1, lastNewLineOffset = -1;
|
||||||
var line = 1, lastNewLineOffset = -1;
|
do {
|
||||||
do {
|
if (desiredLine === line) {
|
||||||
if (desiredLine === line) {
|
return lastNewLineOffset + 1 + desiredCol - 1;
|
||||||
return lastNewLineOffset + 1 + desiredCol - 1;
|
}
|
||||||
}
|
lastNewLineOffset = str.indexOf('\n', lastNewLineOffset + 1);
|
||||||
lastNewLineOffset = str.indexOf('\n', lastNewLineOffset + 1);
|
line++;
|
||||||
line++;
|
} while (lastNewLineOffset >= 0);
|
||||||
} while (lastNewLineOffset >= 0);
|
return -1;
|
||||||
return -1;
|
}
|
||||||
}
|
/**
|
||||||
/**
|
* Return a set of reachable nodes in `graph` starting from `rootNodes`
|
||||||
* Return a set of reachable nodes in `graph` starting from `rootNodes`
|
*/
|
||||||
*/
|
function visit(rootNodes, graph) {
|
||||||
function visit(rootNodes, graph) {
|
var result = {}, queue = rootNodes;
|
||||||
var result = {}, queue = rootNodes;
|
rootNodes.forEach(function (node) {
|
||||||
rootNodes.forEach(function (node) {
|
result[node] = true;
|
||||||
result[node] = true;
|
});
|
||||||
});
|
while (queue.length > 0) {
|
||||||
while (queue.length > 0) {
|
var el = queue.shift();
|
||||||
var el = queue.shift();
|
var myEdges = graph[el] || [];
|
||||||
var myEdges = graph[el] || [];
|
myEdges.forEach(function (toNode) {
|
||||||
myEdges.forEach(function (toNode) {
|
if (!result[toNode]) {
|
||||||
if (!result[toNode]) {
|
result[toNode] = true;
|
||||||
result[toNode] = true;
|
queue.push(toNode);
|
||||||
queue.push(toNode);
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
}
|
return result;
|
||||||
return result;
|
}
|
||||||
}
|
/**
|
||||||
/**
|
* Perform a topological sort on `graph`
|
||||||
* Perform a topological sort on `graph`
|
*/
|
||||||
*/
|
function topologicalSort(graph) {
|
||||||
function topologicalSort(graph) {
|
var allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
|
||||||
var allNodes = {}, outgoingEdgeCount = {}, inverseEdges = {};
|
Object.keys(graph).forEach(function (fromNode) {
|
||||||
Object.keys(graph).forEach(function (fromNode) {
|
allNodes[fromNode] = true;
|
||||||
allNodes[fromNode] = true;
|
outgoingEdgeCount[fromNode] = graph[fromNode].length;
|
||||||
outgoingEdgeCount[fromNode] = graph[fromNode].length;
|
graph[fromNode].forEach(function (toNode) {
|
||||||
graph[fromNode].forEach(function (toNode) {
|
allNodes[toNode] = true;
|
||||||
allNodes[toNode] = true;
|
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
|
||||||
outgoingEdgeCount[toNode] = outgoingEdgeCount[toNode] || 0;
|
inverseEdges[toNode] = inverseEdges[toNode] || [];
|
||||||
inverseEdges[toNode] = inverseEdges[toNode] || [];
|
inverseEdges[toNode].push(fromNode);
|
||||||
inverseEdges[toNode].push(fromNode);
|
});
|
||||||
});
|
});
|
||||||
});
|
// https://en.wikipedia.org/wiki/Topological_sorting
|
||||||
// https://en.wikipedia.org/wiki/Topological_sorting
|
var S = [], L = [];
|
||||||
var S = [], L = [];
|
Object.keys(allNodes).forEach(function (node) {
|
||||||
Object.keys(allNodes).forEach(function (node) {
|
if (outgoingEdgeCount[node] === 0) {
|
||||||
if (outgoingEdgeCount[node] === 0) {
|
delete outgoingEdgeCount[node];
|
||||||
delete outgoingEdgeCount[node];
|
S.push(node);
|
||||||
S.push(node);
|
}
|
||||||
}
|
});
|
||||||
});
|
while (S.length > 0) {
|
||||||
while (S.length > 0) {
|
// Ensure the exact same order all the time with the same inputs
|
||||||
// Ensure the exact same order all the time with the same inputs
|
S.sort();
|
||||||
S.sort();
|
var n = S.shift();
|
||||||
var n = S.shift();
|
L.push(n);
|
||||||
L.push(n);
|
var myInverseEdges = inverseEdges[n] || [];
|
||||||
var myInverseEdges = inverseEdges[n] || [];
|
myInverseEdges.forEach(function (m) {
|
||||||
myInverseEdges.forEach(function (m) {
|
outgoingEdgeCount[m]--;
|
||||||
outgoingEdgeCount[m]--;
|
if (outgoingEdgeCount[m] === 0) {
|
||||||
if (outgoingEdgeCount[m] === 0) {
|
delete outgoingEdgeCount[m];
|
||||||
delete outgoingEdgeCount[m];
|
S.push(m);
|
||||||
S.push(m);
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
}
|
if (Object.keys(outgoingEdgeCount).length > 0) {
|
||||||
if (Object.keys(outgoingEdgeCount).length > 0) {
|
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
|
||||||
throw new Error('Cannot do topological sort on cyclic graph, remaining nodes: ' + Object.keys(outgoingEdgeCount));
|
}
|
||||||
}
|
return L;
|
||||||
return L;
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,171 +1,170 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var gulp = require("gulp");
|
||||||
var gulp = require("gulp");
|
var tsb = require("gulp-tsb");
|
||||||
var tsb = require("gulp-tsb");
|
var es = require("event-stream");
|
||||||
var es = require("event-stream");
|
var watch = require('./watch');
|
||||||
var watch = require('./watch');
|
var nls = require("./nls");
|
||||||
var nls = require("./nls");
|
var util = require("./util");
|
||||||
var util = require("./util");
|
var reporter_1 = require("./reporter");
|
||||||
var reporter_1 = require("./reporter");
|
var path = require("path");
|
||||||
var path = require("path");
|
var bom = require("gulp-bom");
|
||||||
var bom = require("gulp-bom");
|
var sourcemaps = require("gulp-sourcemaps");
|
||||||
var sourcemaps = require("gulp-sourcemaps");
|
var _ = require("underscore");
|
||||||
var _ = require("underscore");
|
var monacodts = require("../monaco/api");
|
||||||
var monacodts = require("../monaco/api");
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
var reporter = reporter_1.createReporter();
|
||||||
var reporter = reporter_1.createReporter();
|
var rootDir = path.join(__dirname, '../../src');
|
||||||
var rootDir = path.join(__dirname, '../../src');
|
var options = require('../../src/tsconfig.json').compilerOptions;
|
||||||
var options = require('../../src/tsconfig.json').compilerOptions;
|
options.verbose = false;
|
||||||
options.verbose = false;
|
options.sourceMap = true;
|
||||||
options.sourceMap = true;
|
options.rootDir = rootDir;
|
||||||
options.rootDir = rootDir;
|
options.sourceRoot = util.toFileUri(rootDir);
|
||||||
options.sourceRoot = util.toFileUri(rootDir);
|
function createCompile(build, emitError) {
|
||||||
function createCompile(build, emitError) {
|
var opts = _.clone(options);
|
||||||
var opts = _.clone(options);
|
opts.inlineSources = !!build;
|
||||||
opts.inlineSources = !!build;
|
opts.noFilesystemLookup = true;
|
||||||
opts.noFilesystemLookup = true;
|
var ts = tsb.create(opts, null, null, function (err) { return reporter(err.toString()); });
|
||||||
var ts = tsb.create(opts, null, null, function (err) { return reporter(err.toString()); });
|
return function (token) {
|
||||||
return function (token) {
|
var utf8Filter = util.filter(function (data) { return /(\/|\\)test(\/|\\).*utf8/.test(data.path); });
|
||||||
var utf8Filter = util.filter(function (data) { return /(\/|\\)test(\/|\\).*utf8/.test(data.path); });
|
var tsFilter = util.filter(function (data) { return /\.ts$/.test(data.path); });
|
||||||
var tsFilter = util.filter(function (data) { return /\.ts$/.test(data.path); });
|
var noDeclarationsFilter = util.filter(function (data) { return !(/\.d\.ts$/.test(data.path)); });
|
||||||
var noDeclarationsFilter = util.filter(function (data) { return !(/\.d\.ts$/.test(data.path)); });
|
var input = es.through();
|
||||||
var input = es.through();
|
var output = input
|
||||||
var output = input
|
.pipe(utf8Filter)
|
||||||
.pipe(utf8Filter)
|
.pipe(bom())
|
||||||
.pipe(bom())
|
.pipe(utf8Filter.restore)
|
||||||
.pipe(utf8Filter.restore)
|
.pipe(tsFilter)
|
||||||
.pipe(tsFilter)
|
.pipe(util.loadSourcemaps())
|
||||||
.pipe(util.loadSourcemaps())
|
.pipe(ts(token))
|
||||||
.pipe(ts(token))
|
.pipe(build ? reloadTypeScriptNodeModule() : es.through())
|
||||||
.pipe(build ? reloadTypeScriptNodeModule() : es.through())
|
.pipe(noDeclarationsFilter)
|
||||||
.pipe(noDeclarationsFilter)
|
.pipe(build ? nls() : es.through())
|
||||||
.pipe(build ? nls() : es.through())
|
.pipe(noDeclarationsFilter.restore)
|
||||||
.pipe(noDeclarationsFilter.restore)
|
.pipe(sourcemaps.write('.', {
|
||||||
.pipe(sourcemaps.write('.', {
|
addComment: false,
|
||||||
addComment: false,
|
includeContent: !!build,
|
||||||
includeContent: !!build,
|
sourceRoot: options.sourceRoot
|
||||||
sourceRoot: options.sourceRoot
|
}))
|
||||||
}))
|
.pipe(tsFilter.restore)
|
||||||
.pipe(tsFilter.restore)
|
.pipe(reporter.end(emitError));
|
||||||
.pipe(reporter.end(emitError));
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
};
|
||||||
};
|
}
|
||||||
}
|
function compileTask(out, build) {
|
||||||
function compileTask(out, build) {
|
return function () {
|
||||||
return function () {
|
var compile = createCompile(build, true);
|
||||||
var compile = createCompile(build, true);
|
var src = es.merge(gulp.src('src/**', { base: 'src' }), gulp.src('node_modules/typescript/lib/lib.d.ts'), gulp.src('node_modules/@types/**/index.d.ts'));
|
||||||
var src = es.merge(gulp.src('src/**', { base: 'src' }), gulp.src('node_modules/typescript/lib/lib.d.ts'), gulp.src('node_modules/@types/**/index.d.ts'));
|
return src
|
||||||
return src
|
.pipe(compile())
|
||||||
.pipe(compile())
|
.pipe(gulp.dest(out))
|
||||||
.pipe(gulp.dest(out))
|
.pipe(monacodtsTask(out, false));
|
||||||
.pipe(monacodtsTask(out, false));
|
};
|
||||||
};
|
}
|
||||||
}
|
exports.compileTask = compileTask;
|
||||||
exports.compileTask = compileTask;
|
function watchTask(out, build) {
|
||||||
function watchTask(out, build) {
|
return function () {
|
||||||
return function () {
|
var compile = createCompile(build);
|
||||||
var compile = createCompile(build);
|
var src = es.merge(gulp.src('src/**', { base: 'src' }), gulp.src('node_modules/typescript/lib/lib.d.ts'), gulp.src('node_modules/@types/**/index.d.ts'));
|
||||||
var src = es.merge(gulp.src('src/**', { base: 'src' }), gulp.src('node_modules/typescript/lib/lib.d.ts'), gulp.src('node_modules/@types/**/index.d.ts'));
|
var watchSrc = watch('src/**', { base: 'src' });
|
||||||
var watchSrc = watch('src/**', { base: 'src' });
|
return watchSrc
|
||||||
return watchSrc
|
.pipe(util.incremental(compile, src, true))
|
||||||
.pipe(util.incremental(compile, src, true))
|
.pipe(gulp.dest(out))
|
||||||
.pipe(gulp.dest(out))
|
.pipe(monacodtsTask(out, true));
|
||||||
.pipe(monacodtsTask(out, true));
|
};
|
||||||
};
|
}
|
||||||
}
|
exports.watchTask = watchTask;
|
||||||
exports.watchTask = watchTask;
|
function reloadTypeScriptNodeModule() {
|
||||||
function reloadTypeScriptNodeModule() {
|
var util = require('gulp-util');
|
||||||
var util = require('gulp-util');
|
function log(message) {
|
||||||
function log(message) {
|
var rest = [];
|
||||||
var rest = [];
|
for (var _i = 1; _i < arguments.length; _i++) {
|
||||||
for (var _i = 1; _i < arguments.length; _i++) {
|
rest[_i - 1] = arguments[_i];
|
||||||
rest[_i - 1] = arguments[_i];
|
}
|
||||||
}
|
util.log.apply(util, [util.colors.cyan('[memory watch dog]'), message].concat(rest));
|
||||||
util.log.apply(util, [util.colors.cyan('[memory watch dog]'), message].concat(rest));
|
}
|
||||||
}
|
function heapUsed() {
|
||||||
function heapUsed() {
|
return (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2) + ' MB';
|
||||||
return (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2) + ' MB';
|
}
|
||||||
}
|
return es.through(function (data) {
|
||||||
return es.through(function (data) {
|
this.emit('data', data);
|
||||||
this.emit('data', data);
|
}, function () {
|
||||||
}, function () {
|
log('memory usage after compilation finished: ' + heapUsed());
|
||||||
log('memory usage after compilation finished: ' + heapUsed());
|
// It appears we are running into some variant of
|
||||||
// It appears we are running into some variant of
|
// https://bugs.chromium.org/p/v8/issues/detail?id=2073
|
||||||
// https://bugs.chromium.org/p/v8/issues/detail?id=2073
|
//
|
||||||
//
|
// Even though all references are dropped, some
|
||||||
// Even though all references are dropped, some
|
// optimized methods in the TS compiler end up holding references
|
||||||
// optimized methods in the TS compiler end up holding references
|
// to the entire TypeScript language host (>600MB)
|
||||||
// to the entire TypeScript language host (>600MB)
|
//
|
||||||
//
|
// The idea is to force v8 to drop references to these
|
||||||
// The idea is to force v8 to drop references to these
|
// optimized methods, by "reloading" the typescript node module
|
||||||
// optimized methods, by "reloading" the typescript node module
|
log('Reloading typescript node module...');
|
||||||
log('Reloading typescript node module...');
|
var resolvedName = require.resolve('typescript');
|
||||||
var resolvedName = require.resolve('typescript');
|
var originalModule = require.cache[resolvedName];
|
||||||
var originalModule = require.cache[resolvedName];
|
delete require.cache[resolvedName];
|
||||||
delete require.cache[resolvedName];
|
var newExports = require('typescript');
|
||||||
var newExports = require('typescript');
|
require.cache[resolvedName] = originalModule;
|
||||||
require.cache[resolvedName] = originalModule;
|
for (var prop in newExports) {
|
||||||
for (var prop in newExports) {
|
if (newExports.hasOwnProperty(prop)) {
|
||||||
if (newExports.hasOwnProperty(prop)) {
|
originalModule.exports[prop] = newExports[prop];
|
||||||
originalModule.exports[prop] = newExports[prop];
|
}
|
||||||
}
|
}
|
||||||
}
|
log('typescript node module reloaded.');
|
||||||
log('typescript node module reloaded.');
|
this.emit('end');
|
||||||
this.emit('end');
|
});
|
||||||
});
|
}
|
||||||
}
|
function monacodtsTask(out, isWatch) {
|
||||||
function monacodtsTask(out, isWatch) {
|
var neededFiles = {};
|
||||||
var neededFiles = {};
|
monacodts.getFilesToWatch(out).forEach(function (filePath) {
|
||||||
monacodts.getFilesToWatch(out).forEach(function (filePath) {
|
filePath = path.normalize(filePath);
|
||||||
filePath = path.normalize(filePath);
|
neededFiles[filePath] = true;
|
||||||
neededFiles[filePath] = true;
|
});
|
||||||
});
|
var inputFiles = {};
|
||||||
var inputFiles = {};
|
for (var filePath in neededFiles) {
|
||||||
for (var filePath in neededFiles) {
|
if (/\bsrc(\/|\\)vs\b/.test(filePath)) {
|
||||||
if (/\bsrc(\/|\\)vs\b/.test(filePath)) {
|
// This file is needed from source => simply read it now
|
||||||
// This file is needed from source => simply read it now
|
inputFiles[filePath] = fs.readFileSync(filePath).toString();
|
||||||
inputFiles[filePath] = fs.readFileSync(filePath).toString();
|
}
|
||||||
}
|
}
|
||||||
}
|
var setInputFile = function (filePath, contents) {
|
||||||
var setInputFile = function (filePath, contents) {
|
if (inputFiles[filePath] === contents) {
|
||||||
if (inputFiles[filePath] === contents) {
|
// no change
|
||||||
// no change
|
return;
|
||||||
return;
|
}
|
||||||
}
|
inputFiles[filePath] = contents;
|
||||||
inputFiles[filePath] = contents;
|
var neededInputFilesCount = Object.keys(neededFiles).length;
|
||||||
var neededInputFilesCount = Object.keys(neededFiles).length;
|
var availableInputFilesCount = Object.keys(inputFiles).length;
|
||||||
var availableInputFilesCount = Object.keys(inputFiles).length;
|
if (neededInputFilesCount === availableInputFilesCount) {
|
||||||
if (neededInputFilesCount === availableInputFilesCount) {
|
run();
|
||||||
run();
|
}
|
||||||
}
|
};
|
||||||
};
|
var run = function () {
|
||||||
var run = function () {
|
var result = monacodts.run(out, inputFiles);
|
||||||
var result = monacodts.run(out, inputFiles);
|
if (!result.isTheSame) {
|
||||||
if (!result.isTheSame) {
|
if (isWatch) {
|
||||||
if (isWatch) {
|
fs.writeFileSync(result.filePath, result.content);
|
||||||
fs.writeFileSync(result.filePath, result.content);
|
}
|
||||||
}
|
else {
|
||||||
else {
|
resultStream.emit('error', 'monaco.d.ts is no longer up to date. Please run gulp watch and commit the new file.');
|
||||||
resultStream.emit('error', 'monaco.d.ts is no longer up to date. Please run gulp watch and commit the new file.');
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
};
|
var resultStream;
|
||||||
var resultStream;
|
if (isWatch) {
|
||||||
if (isWatch) {
|
watch('build/monaco/*').pipe(es.through(function () {
|
||||||
watch('build/monaco/*').pipe(es.through(function () {
|
run();
|
||||||
run();
|
}));
|
||||||
}));
|
}
|
||||||
}
|
resultStream = es.through(function (data) {
|
||||||
resultStream = es.through(function (data) {
|
var filePath = path.normalize(data.path);
|
||||||
var filePath = path.normalize(data.path);
|
if (neededFiles[filePath]) {
|
||||||
if (neededFiles[filePath]) {
|
setInputFile(filePath, data.contents.toString());
|
||||||
setInputFile(filePath, data.contents.toString());
|
}
|
||||||
}
|
this.emit('data', data);
|
||||||
this.emit('data', data);
|
});
|
||||||
});
|
return resultStream;
|
||||||
return resultStream;
|
}
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,96 +1,95 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var event_stream_1 = require("event-stream");
|
||||||
var event_stream_1 = require("event-stream");
|
var assign = require("object-assign");
|
||||||
var assign = require("object-assign");
|
var remote = require("gulp-remote-src");
|
||||||
var remote = require("gulp-remote-src");
|
var flatmap = require('gulp-flatmap');
|
||||||
var flatmap = require('gulp-flatmap');
|
var vzip = require('gulp-vinyl-zip');
|
||||||
var vzip = require('gulp-vinyl-zip');
|
var filter = require('gulp-filter');
|
||||||
var filter = require('gulp-filter');
|
var rename = require('gulp-rename');
|
||||||
var rename = require('gulp-rename');
|
var util = require('gulp-util');
|
||||||
var util = require('gulp-util');
|
var buffer = require('gulp-buffer');
|
||||||
var buffer = require('gulp-buffer');
|
var json = require('gulp-json-editor');
|
||||||
var json = require('gulp-json-editor');
|
function error(err) {
|
||||||
function error(err) {
|
var result = event_stream_1.through();
|
||||||
var result = event_stream_1.through();
|
setTimeout(function () { return result.emit('error', err); });
|
||||||
setTimeout(function () { return result.emit('error', err); });
|
return result;
|
||||||
return result;
|
}
|
||||||
}
|
var baseHeaders = {
|
||||||
var baseHeaders = {
|
'X-Market-Client-Id': 'VSCode Build',
|
||||||
'X-Market-Client-Id': 'VSCode Build',
|
'User-Agent': 'VSCode Build',
|
||||||
'User-Agent': 'VSCode Build',
|
};
|
||||||
};
|
function src(extensionName, version) {
|
||||||
function src(extensionName, version) {
|
var filterType = 7;
|
||||||
var filterType = 7;
|
var value = extensionName;
|
||||||
var value = extensionName;
|
var criterium = { filterType: filterType, value: value };
|
||||||
var criterium = { filterType: filterType, value: value };
|
var criteria = [criterium];
|
||||||
var criteria = [criterium];
|
var pageNumber = 1;
|
||||||
var pageNumber = 1;
|
var pageSize = 1;
|
||||||
var pageSize = 1;
|
var sortBy = 0;
|
||||||
var sortBy = 0;
|
var sortOrder = 0;
|
||||||
var sortOrder = 0;
|
var flags = 0x1 | 0x2 | 0x80;
|
||||||
var flags = 0x1 | 0x2 | 0x80;
|
var assetTypes = ['Microsoft.VisualStudio.Services.VSIXPackage'];
|
||||||
var assetTypes = ['Microsoft.VisualStudio.Services.VSIXPackage'];
|
var filters = [{ criteria: criteria, pageNumber: pageNumber, pageSize: pageSize, sortBy: sortBy, sortOrder: sortOrder }];
|
||||||
var filters = [{ criteria: criteria, pageNumber: pageNumber, pageSize: pageSize, sortBy: sortBy, sortOrder: sortOrder }];
|
var body = JSON.stringify({ filters: filters, assetTypes: assetTypes, flags: flags });
|
||||||
var body = JSON.stringify({ filters: filters, assetTypes: assetTypes, flags: flags });
|
var headers = assign({}, baseHeaders, {
|
||||||
var headers = assign({}, baseHeaders, {
|
'Content-Type': 'application/json',
|
||||||
'Content-Type': 'application/json',
|
'Accept': 'application/json;api-version=3.0-preview.1',
|
||||||
'Accept': 'application/json;api-version=3.0-preview.1',
|
'Content-Length': body.length
|
||||||
'Content-Length': body.length
|
});
|
||||||
});
|
var options = {
|
||||||
var options = {
|
base: 'https://marketplace.visualstudio.com/_apis/public/gallery',
|
||||||
base: 'https://marketplace.visualstudio.com/_apis/public/gallery',
|
requestOptions: {
|
||||||
requestOptions: {
|
method: 'POST',
|
||||||
method: 'POST',
|
gzip: true,
|
||||||
gzip: true,
|
headers: headers,
|
||||||
headers: headers,
|
body: body
|
||||||
body: body
|
}
|
||||||
}
|
};
|
||||||
};
|
return remote('/extensionquery', options)
|
||||||
return remote('/extensionquery', options)
|
.pipe(flatmap(function (stream, f) {
|
||||||
.pipe(flatmap(function (stream, f) {
|
var rawResult = f.contents.toString('utf8');
|
||||||
var rawResult = f.contents.toString('utf8');
|
var result = JSON.parse(rawResult);
|
||||||
var result = JSON.parse(rawResult);
|
var extension = result.results[0].extensions[0];
|
||||||
var extension = result.results[0].extensions[0];
|
if (!extension) {
|
||||||
if (!extension) {
|
return error("No such extension: " + extension);
|
||||||
return error("No such extension: " + extension);
|
}
|
||||||
}
|
var metadata = {
|
||||||
var metadata = {
|
id: extension.extensionId,
|
||||||
id: extension.extensionId,
|
publisherId: extension.publisher,
|
||||||
publisherId: extension.publisher,
|
publisherDisplayName: extension.publisher.displayName
|
||||||
publisherDisplayName: extension.publisher.displayName
|
};
|
||||||
};
|
var extensionVersion = extension.versions.filter(function (v) { return v.version === version; })[0];
|
||||||
var extensionVersion = extension.versions.filter(function (v) { return v.version === version; })[0];
|
if (!extensionVersion) {
|
||||||
if (!extensionVersion) {
|
return error("No such extension version: " + extensionName + " @ " + version);
|
||||||
return error("No such extension version: " + extensionName + " @ " + version);
|
}
|
||||||
}
|
var asset = extensionVersion.files.filter(function (f) { return f.assetType === 'Microsoft.VisualStudio.Services.VSIXPackage'; })[0];
|
||||||
var asset = extensionVersion.files.filter(function (f) { return f.assetType === 'Microsoft.VisualStudio.Services.VSIXPackage'; })[0];
|
if (!asset) {
|
||||||
if (!asset) {
|
return error("No VSIX found for extension version: " + extensionName + " @ " + version);
|
||||||
return error("No VSIX found for extension version: " + extensionName + " @ " + version);
|
}
|
||||||
}
|
util.log('Downloading extension:', util.colors.yellow(extensionName + "@" + version), '...');
|
||||||
util.log('Downloading extension:', util.colors.yellow(extensionName + "@" + version), '...');
|
var options = {
|
||||||
var options = {
|
base: asset.source,
|
||||||
base: asset.source,
|
requestOptions: {
|
||||||
requestOptions: {
|
gzip: true,
|
||||||
gzip: true,
|
headers: baseHeaders
|
||||||
headers: baseHeaders
|
}
|
||||||
}
|
};
|
||||||
};
|
return remote('', options)
|
||||||
return remote('', options)
|
.pipe(flatmap(function (stream) {
|
||||||
.pipe(flatmap(function (stream) {
|
var packageJsonFilter = filter('package.json', { restore: true });
|
||||||
var packageJsonFilter = filter('package.json', { restore: true });
|
return stream
|
||||||
return stream
|
.pipe(vzip.src())
|
||||||
.pipe(vzip.src())
|
.pipe(filter('extension/**'))
|
||||||
.pipe(filter('extension/**'))
|
.pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\/?/, ''); }))
|
||||||
.pipe(rename(function (p) { return p.dirname = p.dirname.replace(/^extension\/?/, ''); }))
|
.pipe(packageJsonFilter)
|
||||||
.pipe(packageJsonFilter)
|
.pipe(buffer())
|
||||||
.pipe(buffer())
|
.pipe(json({ __metadata: metadata }))
|
||||||
.pipe(json({ __metadata: metadata }))
|
.pipe(packageJsonFilter.restore);
|
||||||
.pipe(packageJsonFilter.restore);
|
}));
|
||||||
}));
|
}));
|
||||||
}));
|
}
|
||||||
}
|
exports.src = src;
|
||||||
exports.src = src;
|
|
||||||
|
|||||||
104
build/lib/git.js
104
build/lib/git.js
@@ -1,53 +1,51 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var path = require("path");
|
||||||
var path = require("path");
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
/**
|
||||||
/**
|
* Returns the sha1 commit version of a repository or undefined in case of failure.
|
||||||
* Returns the sha1 commit version of a repository or undefined in case of failure.
|
*/
|
||||||
*/
|
function getVersion(repo) {
|
||||||
function getVersion(repo) {
|
var git = path.join(repo, '.git');
|
||||||
var git = path.join(repo, '.git');
|
var headPath = path.join(git, 'HEAD');
|
||||||
var headPath = path.join(git, 'HEAD');
|
var head;
|
||||||
var head;
|
try {
|
||||||
try {
|
head = fs.readFileSync(headPath, 'utf8').trim();
|
||||||
head = fs.readFileSync(headPath, 'utf8').trim();
|
}
|
||||||
}
|
catch (e) {
|
||||||
catch (e) {
|
return void 0;
|
||||||
return void 0;
|
}
|
||||||
}
|
if (/^[0-9a-f]{40}$/i.test(head)) {
|
||||||
if (/^[0-9a-f]{40}$/i.test(head)) {
|
return head;
|
||||||
return head;
|
}
|
||||||
}
|
var refMatch = /^ref: (.*)$/.exec(head);
|
||||||
var refMatch = /^ref: (.*)$/.exec(head);
|
if (!refMatch) {
|
||||||
if (!refMatch) {
|
return void 0;
|
||||||
return void 0;
|
}
|
||||||
}
|
var ref = refMatch[1];
|
||||||
var ref = refMatch[1];
|
var refPath = path.join(git, ref);
|
||||||
var refPath = path.join(git, ref);
|
try {
|
||||||
try {
|
return fs.readFileSync(refPath, 'utf8').trim();
|
||||||
return fs.readFileSync(refPath, 'utf8').trim();
|
}
|
||||||
}
|
catch (e) {
|
||||||
catch (e) {
|
}
|
||||||
// noop
|
var packedRefsPath = path.join(git, 'packed-refs');
|
||||||
}
|
var refsRaw;
|
||||||
var packedRefsPath = path.join(git, 'packed-refs');
|
try {
|
||||||
var refsRaw;
|
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
|
||||||
try {
|
}
|
||||||
refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
|
catch (e) {
|
||||||
}
|
return void 0;
|
||||||
catch (e) {
|
}
|
||||||
return void 0;
|
var refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
|
||||||
}
|
var refsMatch;
|
||||||
var refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
|
var refs = {};
|
||||||
var refsMatch;
|
while (refsMatch = refsRegex.exec(refsRaw)) {
|
||||||
var refs = {};
|
refs[refsMatch[2]] = refsMatch[1];
|
||||||
while (refsMatch = refsRegex.exec(refsRaw)) {
|
}
|
||||||
refs[refsMatch[2]] = refsMatch[1];
|
return refs[ref];
|
||||||
}
|
}
|
||||||
return refs[ref];
|
exports.getVersion = getVersion;
|
||||||
}
|
|
||||||
exports.getVersion = getVersion;
|
|
||||||
|
|||||||
@@ -1,290 +1,289 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var path = require("path");
|
||||||
var path = require("path");
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
var event_stream_1 = require("event-stream");
|
||||||
var event_stream_1 = require("event-stream");
|
var File = require("vinyl");
|
||||||
var File = require("vinyl");
|
var Is = require("is");
|
||||||
var Is = require("is");
|
var util = require('gulp-util');
|
||||||
var util = require('gulp-util');
|
function log(message) {
|
||||||
function log(message) {
|
var rest = [];
|
||||||
var rest = [];
|
for (var _i = 1; _i < arguments.length; _i++) {
|
||||||
for (var _i = 1; _i < arguments.length; _i++) {
|
rest[_i - 1] = arguments[_i];
|
||||||
rest[_i - 1] = arguments[_i];
|
}
|
||||||
}
|
util.log.apply(util, [util.colors.green('[i18n]'), message].concat(rest));
|
||||||
util.log.apply(util, [util.colors.green('[i18n]'), message].concat(rest));
|
}
|
||||||
}
|
var LocalizeInfo;
|
||||||
var LocalizeInfo;
|
(function (LocalizeInfo) {
|
||||||
(function (LocalizeInfo) {
|
function is(value) {
|
||||||
function is(value) {
|
var candidate = 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); })));
|
||||||
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.is = is;
|
})(LocalizeInfo || (LocalizeInfo = {}));
|
||||||
})(LocalizeInfo || (LocalizeInfo = {}));
|
var BundledFormat;
|
||||||
var BundledFormat;
|
(function (BundledFormat) {
|
||||||
(function (BundledFormat) {
|
function is(value) {
|
||||||
function is(value) {
|
if (Is.undef(value)) {
|
||||||
if (Is.undef(value)) {
|
return false;
|
||||||
return false;
|
}
|
||||||
}
|
var candidate = value;
|
||||||
var candidate = value;
|
var length = Object.keys(value).length;
|
||||||
var length = Object.keys(value).length;
|
return length === 3 && Is.defined(candidate.keys) && Is.defined(candidate.messages) && Is.defined(candidate.bundles);
|
||||||
return length === 3 && Is.defined(candidate.keys) && Is.defined(candidate.messages) && Is.defined(candidate.bundles);
|
}
|
||||||
}
|
BundledFormat.is = is;
|
||||||
BundledFormat.is = is;
|
})(BundledFormat || (BundledFormat = {}));
|
||||||
})(BundledFormat || (BundledFormat = {}));
|
var vscodeLanguages = [
|
||||||
var vscodeLanguages = [
|
'chs',
|
||||||
'chs',
|
'cht',
|
||||||
'cht',
|
'jpn',
|
||||||
'jpn',
|
'kor',
|
||||||
'kor',
|
'deu',
|
||||||
'deu',
|
'fra',
|
||||||
'fra',
|
'esn',
|
||||||
'esn',
|
'rus',
|
||||||
'rus',
|
'ita'
|
||||||
'ita'
|
];
|
||||||
];
|
var iso639_3_to_2 = {
|
||||||
var iso639_3_to_2 = {
|
'chs': 'zh-cn',
|
||||||
'chs': 'zh-cn',
|
'cht': 'zh-tw',
|
||||||
'cht': 'zh-tw',
|
'csy': 'cs-cz',
|
||||||
'csy': 'cs-cz',
|
'deu': 'de',
|
||||||
'deu': 'de',
|
'enu': 'en',
|
||||||
'enu': 'en',
|
'esn': 'es',
|
||||||
'esn': 'es',
|
'fra': 'fr',
|
||||||
'fra': 'fr',
|
'hun': 'hu',
|
||||||
'hun': 'hu',
|
'ita': 'it',
|
||||||
'ita': 'it',
|
'jpn': 'ja',
|
||||||
'jpn': 'ja',
|
'kor': 'ko',
|
||||||
'kor': 'ko',
|
'nld': 'nl',
|
||||||
'nld': 'nl',
|
'plk': 'pl',
|
||||||
'plk': 'pl',
|
'ptb': 'pt-br',
|
||||||
'ptb': 'pt-br',
|
'ptg': 'pt',
|
||||||
'ptg': 'pt',
|
'rus': 'ru',
|
||||||
'rus': 'ru',
|
'sve': 'sv-se',
|
||||||
'sve': 'sv-se',
|
'trk': 'tr'
|
||||||
'trk': 'tr'
|
};
|
||||||
};
|
function sortLanguages(directoryNames) {
|
||||||
function sortLanguages(directoryNames) {
|
return directoryNames.map(function (dirName) {
|
||||||
return directoryNames.map(function (dirName) {
|
var lower = dirName.toLowerCase();
|
||||||
var lower = dirName.toLowerCase();
|
return {
|
||||||
return {
|
name: lower,
|
||||||
name: lower,
|
iso639_2: iso639_3_to_2[lower]
|
||||||
iso639_2: iso639_3_to_2[lower]
|
};
|
||||||
};
|
}).sort(function (a, b) {
|
||||||
}).sort(function (a, b) {
|
if (!a.iso639_2 && !b.iso639_2) {
|
||||||
if (!a.iso639_2 && !b.iso639_2) {
|
return 0;
|
||||||
return 0;
|
}
|
||||||
}
|
if (!a.iso639_2) {
|
||||||
if (!a.iso639_2) {
|
return -1;
|
||||||
return -1;
|
}
|
||||||
}
|
if (!b.iso639_2) {
|
||||||
if (!b.iso639_2) {
|
return 1;
|
||||||
return 1;
|
}
|
||||||
}
|
return a.iso639_2 < b.iso639_2 ? -1 : (a.iso639_2 > b.iso639_2 ? 1 : 0);
|
||||||
return a.iso639_2 < b.iso639_2 ? -1 : (a.iso639_2 > b.iso639_2 ? 1 : 0);
|
});
|
||||||
});
|
}
|
||||||
}
|
function stripComments(content) {
|
||||||
function stripComments(content) {
|
/**
|
||||||
/**
|
* First capturing group matches double quoted string
|
||||||
* First capturing group matches double quoted string
|
* Second matches single quotes string
|
||||||
* Second matches single quotes string
|
* Third matches block comments
|
||||||
* Third matches block comments
|
* Fourth matches line comments
|
||||||
* Fourth matches line comments
|
*/
|
||||||
*/
|
var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
|
||||||
var regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
|
var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
|
||||||
var result = content.replace(regexp, function (match, m1, m2, m3, m4) {
|
// Only one of m1, m2, m3, m4 matches
|
||||||
// Only one of m1, m2, m3, m4 matches
|
if (m3) {
|
||||||
if (m3) {
|
// A block comment. Replace with nothing
|
||||||
// A block comment. Replace with nothing
|
return '';
|
||||||
return '';
|
}
|
||||||
}
|
else if (m4) {
|
||||||
else if (m4) {
|
// A line comment. If it ends in \r?\n then keep it.
|
||||||
// A line comment. If it ends in \r?\n then keep it.
|
var length_1 = m4.length;
|
||||||
var length_1 = m4.length;
|
if (length_1 > 2 && m4[length_1 - 1] === '\n') {
|
||||||
if (length_1 > 2 && m4[length_1 - 1] === '\n') {
|
return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
|
||||||
return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
|
}
|
||||||
}
|
else {
|
||||||
else {
|
return '';
|
||||||
return '';
|
}
|
||||||
}
|
}
|
||||||
}
|
else {
|
||||||
else {
|
// We match a string
|
||||||
// We match a string
|
return match;
|
||||||
return match;
|
}
|
||||||
}
|
});
|
||||||
});
|
return result;
|
||||||
return result;
|
}
|
||||||
}
|
;
|
||||||
;
|
function escapeCharacters(value) {
|
||||||
function escapeCharacters(value) {
|
var result = [];
|
||||||
var result = [];
|
for (var i = 0; i < value.length; i++) {
|
||||||
for (var i = 0; i < value.length; i++) {
|
var ch = value.charAt(i);
|
||||||
var ch = value.charAt(i);
|
switch (ch) {
|
||||||
switch (ch) {
|
case '\'':
|
||||||
case '\'':
|
result.push('\\\'');
|
||||||
result.push('\\\'');
|
break;
|
||||||
break;
|
case '"':
|
||||||
case '"':
|
result.push('\\"');
|
||||||
result.push('\\"');
|
break;
|
||||||
break;
|
case '\\':
|
||||||
case '\\':
|
result.push('\\\\');
|
||||||
result.push('\\\\');
|
break;
|
||||||
break;
|
case '\n':
|
||||||
case '\n':
|
result.push('\\n');
|
||||||
result.push('\\n');
|
break;
|
||||||
break;
|
case '\r':
|
||||||
case '\r':
|
result.push('\\r');
|
||||||
result.push('\\r');
|
break;
|
||||||
break;
|
case '\t':
|
||||||
case '\t':
|
result.push('\\t');
|
||||||
result.push('\\t');
|
break;
|
||||||
break;
|
case '\b':
|
||||||
case '\b':
|
result.push('\\b');
|
||||||
result.push('\\b');
|
break;
|
||||||
break;
|
case '\f':
|
||||||
case '\f':
|
result.push('\\f');
|
||||||
result.push('\\f');
|
break;
|
||||||
break;
|
default:
|
||||||
default:
|
result.push(ch);
|
||||||
result.push(ch);
|
}
|
||||||
}
|
}
|
||||||
}
|
return result.join('');
|
||||||
return result.join('');
|
}
|
||||||
}
|
function processCoreBundleFormat(fileHeader, json, emitter) {
|
||||||
function processCoreBundleFormat(fileHeader, json, emitter) {
|
var keysSection = json.keys;
|
||||||
var keysSection = json.keys;
|
var messageSection = json.messages;
|
||||||
var messageSection = json.messages;
|
var bundleSection = json.bundles;
|
||||||
var bundleSection = json.bundles;
|
var statistics = Object.create(null);
|
||||||
var statistics = Object.create(null);
|
var total = 0;
|
||||||
var total = 0;
|
var defaultMessages = Object.create(null);
|
||||||
var defaultMessages = Object.create(null);
|
var modules = Object.keys(keysSection);
|
||||||
var modules = Object.keys(keysSection);
|
modules.forEach(function (module) {
|
||||||
modules.forEach(function (module) {
|
var keys = keysSection[module];
|
||||||
var keys = keysSection[module];
|
var messages = messageSection[module];
|
||||||
var messages = messageSection[module];
|
if (!messages || keys.length !== messages.length) {
|
||||||
if (!messages || keys.length !== messages.length) {
|
emitter.emit('error', "Message for module " + module + " corrupted. Mismatch in number of keys and messages.");
|
||||||
emitter.emit('error', "Message for module " + module + " corrupted. Mismatch in number of keys and messages.");
|
return;
|
||||||
return;
|
}
|
||||||
}
|
var messageMap = Object.create(null);
|
||||||
var messageMap = Object.create(null);
|
defaultMessages[module] = messageMap;
|
||||||
defaultMessages[module] = messageMap;
|
keys.map(function (key, i) {
|
||||||
keys.map(function (key, i) {
|
total++;
|
||||||
total++;
|
if (Is.string(key)) {
|
||||||
if (Is.string(key)) {
|
messageMap[key] = messages[i];
|
||||||
messageMap[key] = messages[i];
|
}
|
||||||
}
|
else {
|
||||||
else {
|
messageMap[key.key] = messages[i];
|
||||||
messageMap[key.key] = messages[i];
|
}
|
||||||
}
|
});
|
||||||
});
|
});
|
||||||
});
|
var languageDirectory = path.join(__dirname, '..', '..', 'i18n');
|
||||||
var languageDirectory = path.join(__dirname, '..', '..', 'i18n');
|
var languages = sortLanguages(fs.readdirSync(languageDirectory).filter(function (item) { return fs.statSync(path.join(languageDirectory, item)).isDirectory(); }));
|
||||||
var languages = sortLanguages(fs.readdirSync(languageDirectory).filter(function (item) { return fs.statSync(path.join(languageDirectory, item)).isDirectory(); }));
|
languages.forEach(function (language) {
|
||||||
languages.forEach(function (language) {
|
if (!language.iso639_2) {
|
||||||
if (!language.iso639_2) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
||||||
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
log("Generating nls bundles for: " + language.iso639_2);
|
||||||
log("Generating nls bundles for: " + language.iso639_2);
|
}
|
||||||
}
|
statistics[language.iso639_2] = 0;
|
||||||
statistics[language.iso639_2] = 0;
|
var localizedModules = Object.create(null);
|
||||||
var localizedModules = Object.create(null);
|
var cwd = path.join(languageDirectory, language.name, 'src');
|
||||||
var cwd = path.join(languageDirectory, language.name, 'src');
|
modules.forEach(function (module) {
|
||||||
modules.forEach(function (module) {
|
var order = keysSection[module];
|
||||||
var order = keysSection[module];
|
var i18nFile = path.join(cwd, module) + '.i18n.json';
|
||||||
var i18nFile = path.join(cwd, module) + '.i18n.json';
|
var messages = null;
|
||||||
var messages = null;
|
if (fs.existsSync(i18nFile)) {
|
||||||
if (fs.existsSync(i18nFile)) {
|
var content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
|
||||||
var content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
|
messages = JSON.parse(content);
|
||||||
messages = JSON.parse(content);
|
}
|
||||||
}
|
else {
|
||||||
else {
|
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
||||||
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
log("No localized messages found for module " + module + ". Using default messages.");
|
||||||
log("No localized messages found for module " + module + ". Using default messages.");
|
}
|
||||||
}
|
messages = defaultMessages[module];
|
||||||
messages = defaultMessages[module];
|
statistics[language.iso639_2] = statistics[language.iso639_2] + Object.keys(messages).length;
|
||||||
statistics[language.iso639_2] = statistics[language.iso639_2] + Object.keys(messages).length;
|
}
|
||||||
}
|
var localizedMessages = [];
|
||||||
var localizedMessages = [];
|
order.forEach(function (keyInfo) {
|
||||||
order.forEach(function (keyInfo) {
|
var key = null;
|
||||||
var key = null;
|
if (Is.string(keyInfo)) {
|
||||||
if (Is.string(keyInfo)) {
|
key = keyInfo;
|
||||||
key = keyInfo;
|
}
|
||||||
}
|
else {
|
||||||
else {
|
key = keyInfo.key;
|
||||||
key = keyInfo.key;
|
}
|
||||||
}
|
var message = messages[key];
|
||||||
var message = messages[key];
|
if (!message) {
|
||||||
if (!message) {
|
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
||||||
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
log("No localized message found for key " + key + " in module " + module + ". Using default message.");
|
||||||
log("No localized message found for key " + key + " in module " + module + ". Using default message.");
|
}
|
||||||
}
|
message = defaultMessages[module][key];
|
||||||
message = defaultMessages[module][key];
|
statistics[language.iso639_2] = statistics[language.iso639_2] + 1;
|
||||||
statistics[language.iso639_2] = statistics[language.iso639_2] + 1;
|
}
|
||||||
}
|
localizedMessages.push(message);
|
||||||
localizedMessages.push(message);
|
});
|
||||||
});
|
localizedModules[module] = localizedMessages;
|
||||||
localizedModules[module] = localizedMessages;
|
});
|
||||||
});
|
Object.keys(bundleSection).forEach(function (bundle) {
|
||||||
Object.keys(bundleSection).forEach(function (bundle) {
|
var modules = bundleSection[bundle];
|
||||||
var modules = bundleSection[bundle];
|
var contents = [
|
||||||
var contents = [
|
fileHeader,
|
||||||
fileHeader,
|
"define(\"" + bundle + ".nls." + language.iso639_2 + "\", {"
|
||||||
"define(\"" + bundle + ".nls." + language.iso639_2 + "\", {"
|
];
|
||||||
];
|
modules.forEach(function (module, index) {
|
||||||
modules.forEach(function (module, index) {
|
contents.push("\t\"" + module + "\": [");
|
||||||
contents.push("\t\"" + module + "\": [");
|
var messages = localizedModules[module];
|
||||||
var messages = localizedModules[module];
|
if (!messages) {
|
||||||
if (!messages) {
|
emitter.emit('error', "Didn't find messages for module " + module + ".");
|
||||||
emitter.emit('error', "Didn't find messages for module " + module + ".");
|
return;
|
||||||
return;
|
}
|
||||||
}
|
messages.forEach(function (message, index) {
|
||||||
messages.forEach(function (message, index) {
|
contents.push("\t\t\"" + escapeCharacters(message) + (index < messages.length ? '",' : '"'));
|
||||||
contents.push("\t\t\"" + escapeCharacters(message) + (index < messages.length ? '",' : '"'));
|
});
|
||||||
});
|
contents.push(index < modules.length - 1 ? '\t],' : '\t]');
|
||||||
contents.push(index < modules.length - 1 ? '\t],' : '\t]');
|
});
|
||||||
});
|
contents.push('});');
|
||||||
contents.push('});');
|
emitter.emit('data', new File({ path: bundle + '.nls.' + language.iso639_2 + '.js', contents: new Buffer(contents.join('\n'), 'utf-8') }));
|
||||||
emitter.emit('data', new File({ path: bundle + '.nls.' + language.iso639_2 + '.js', contents: new Buffer(contents.join('\n'), 'utf-8') }));
|
});
|
||||||
});
|
});
|
||||||
});
|
Object.keys(statistics).forEach(function (key) {
|
||||||
Object.keys(statistics).forEach(function (key) {
|
var value = statistics[key];
|
||||||
var value = statistics[key];
|
log(key + " has " + value + " untranslated strings.");
|
||||||
log(key + " has " + value + " untranslated strings.");
|
});
|
||||||
});
|
vscodeLanguages.forEach(function (language) {
|
||||||
vscodeLanguages.forEach(function (language) {
|
var iso639_2 = iso639_3_to_2[language];
|
||||||
var iso639_2 = iso639_3_to_2[language];
|
if (!iso639_2) {
|
||||||
if (!iso639_2) {
|
log("\tCouldn't find iso639 2 mapping for language " + language + ". Using default language instead.");
|
||||||
log("\tCouldn't find iso639 2 mapping for language " + language + ". Using default language instead.");
|
}
|
||||||
}
|
else {
|
||||||
else {
|
var stats = statistics[iso639_2];
|
||||||
var stats = statistics[iso639_2];
|
if (Is.undef(stats)) {
|
||||||
if (Is.undef(stats)) {
|
log("\tNo translations found for language " + language + ". Using default language instead.");
|
||||||
log("\tNo translations found for language " + language + ". Using default language instead.");
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
}
|
function processNlsFiles(opts) {
|
||||||
function processNlsFiles(opts) {
|
return event_stream_1.through(function (file) {
|
||||||
return event_stream_1.through(function (file) {
|
var fileName = path.basename(file.path);
|
||||||
var fileName = path.basename(file.path);
|
if (fileName === 'nls.metadata.json') {
|
||||||
if (fileName === 'nls.metadata.json') {
|
var json = null;
|
||||||
var json = null;
|
if (file.isBuffer()) {
|
||||||
if (file.isBuffer()) {
|
json = JSON.parse(file.contents.toString('utf8'));
|
||||||
json = JSON.parse(file.contents.toString('utf8'));
|
}
|
||||||
}
|
else {
|
||||||
else {
|
this.emit('error', "Failed to read component file: " + file.relative);
|
||||||
this.emit('error', "Failed to read component file: " + file.relative);
|
}
|
||||||
}
|
if (BundledFormat.is(json)) {
|
||||||
if (BundledFormat.is(json)) {
|
processCoreBundleFormat(opts.fileHeader, json, this);
|
||||||
processCoreBundleFormat(opts.fileHeader, json, this);
|
}
|
||||||
}
|
}
|
||||||
}
|
this.emit('data', file);
|
||||||
this.emit('data', file);
|
});
|
||||||
});
|
}
|
||||||
}
|
exports.processNlsFiles = processNlsFiles;
|
||||||
exports.processNlsFiles = processNlsFiles;
|
|
||||||
|
|||||||
710
build/lib/nls.js
710
build/lib/nls.js
@@ -1,355 +1,355 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var ts = require("./typescript/typescriptServices");
|
var ts = require("./typescript/typescriptServices");
|
||||||
var lazy = require("lazy.js");
|
var lazy = require("lazy.js");
|
||||||
var event_stream_1 = require("event-stream");
|
var event_stream_1 = require("event-stream");
|
||||||
var File = require("vinyl");
|
var File = require("vinyl");
|
||||||
var sm = require("source-map");
|
var sm = require("source-map");
|
||||||
var assign = require("object-assign");
|
var assign = require("object-assign");
|
||||||
var path = require("path");
|
var path = require("path");
|
||||||
var CollectStepResult;
|
var CollectStepResult;
|
||||||
(function (CollectStepResult) {
|
(function (CollectStepResult) {
|
||||||
CollectStepResult[CollectStepResult["Yes"] = 0] = "Yes";
|
CollectStepResult[CollectStepResult["Yes"] = 0] = "Yes";
|
||||||
CollectStepResult[CollectStepResult["YesAndRecurse"] = 1] = "YesAndRecurse";
|
CollectStepResult[CollectStepResult["YesAndRecurse"] = 1] = "YesAndRecurse";
|
||||||
CollectStepResult[CollectStepResult["No"] = 2] = "No";
|
CollectStepResult[CollectStepResult["No"] = 2] = "No";
|
||||||
CollectStepResult[CollectStepResult["NoAndRecurse"] = 3] = "NoAndRecurse";
|
CollectStepResult[CollectStepResult["NoAndRecurse"] = 3] = "NoAndRecurse";
|
||||||
})(CollectStepResult || (CollectStepResult = {}));
|
})(CollectStepResult || (CollectStepResult = {}));
|
||||||
function collect(node, fn) {
|
function collect(node, fn) {
|
||||||
var result = [];
|
var result = [];
|
||||||
function loop(node) {
|
function loop(node) {
|
||||||
var stepResult = fn(node);
|
var stepResult = fn(node);
|
||||||
if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) {
|
if (stepResult === CollectStepResult.Yes || stepResult === CollectStepResult.YesAndRecurse) {
|
||||||
result.push(node);
|
result.push(node);
|
||||||
}
|
}
|
||||||
if (stepResult === CollectStepResult.YesAndRecurse || stepResult === CollectStepResult.NoAndRecurse) {
|
if (stepResult === CollectStepResult.YesAndRecurse || stepResult === CollectStepResult.NoAndRecurse) {
|
||||||
ts.forEachChild(node, loop);
|
ts.forEachChild(node, loop);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loop(node);
|
loop(node);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
function clone(object) {
|
function clone(object) {
|
||||||
var result = {};
|
var result = {};
|
||||||
for (var id in object) {
|
for (var id in object) {
|
||||||
result[id] = object[id];
|
result[id] = object[id];
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
function template(lines) {
|
function template(lines) {
|
||||||
var indent = '', wrap = '';
|
var indent = '', wrap = '';
|
||||||
if (lines.length > 1) {
|
if (lines.length > 1) {
|
||||||
indent = '\t';
|
indent = '\t';
|
||||||
wrap = '\n';
|
wrap = '\n';
|
||||||
}
|
}
|
||||||
return "/*---------------------------------------------------------\n * Copyright (C) Microsoft Corporation. All rights reserved.\n *--------------------------------------------------------*/\ndefine([], [" + (wrap + lines.map(function (l) { return indent + l; }).join(',\n') + wrap) + "]);";
|
return "/*---------------------------------------------------------\n * Copyright (C) Microsoft Corporation. All rights reserved.\n *--------------------------------------------------------*/\ndefine([], [" + (wrap + lines.map(function (l) { return indent + l; }).join(',\n') + wrap) + "]);";
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Returns a stream containing the patched JavaScript and source maps.
|
* Returns a stream containing the patched JavaScript and source maps.
|
||||||
*/
|
*/
|
||||||
function nls() {
|
function nls() {
|
||||||
var input = event_stream_1.through();
|
var input = event_stream_1.through();
|
||||||
var output = input.pipe(event_stream_1.through(function (f) {
|
var output = input.pipe(event_stream_1.through(function (f) {
|
||||||
var _this = this;
|
var _this = this;
|
||||||
if (!f.sourceMap) {
|
if (!f.sourceMap) {
|
||||||
return this.emit('error', new Error("File " + f.relative + " does not have sourcemaps."));
|
return this.emit('error', new Error("File " + f.relative + " does not have sourcemaps."));
|
||||||
}
|
}
|
||||||
var source = f.sourceMap.sources[0];
|
var source = f.sourceMap.sources[0];
|
||||||
if (!source) {
|
if (!source) {
|
||||||
return this.emit('error', new Error("File " + f.relative + " does not have a source in the source map."));
|
return this.emit('error', new Error("File " + f.relative + " does not have a source in the source map."));
|
||||||
}
|
}
|
||||||
var root = f.sourceMap.sourceRoot;
|
var root = f.sourceMap.sourceRoot;
|
||||||
if (root) {
|
if (root) {
|
||||||
source = path.join(root, source);
|
source = path.join(root, source);
|
||||||
}
|
}
|
||||||
var typescript = f.sourceMap.sourcesContent[0];
|
var typescript = f.sourceMap.sourcesContent[0];
|
||||||
if (!typescript) {
|
if (!typescript) {
|
||||||
return this.emit('error', new Error("File " + f.relative + " does not have the original content in the source map."));
|
return this.emit('error', new Error("File " + f.relative + " does not have the original content in the source map."));
|
||||||
}
|
}
|
||||||
nls.patchFiles(f, typescript).forEach(function (f) { return _this.emit('data', f); });
|
nls.patchFiles(f, typescript).forEach(function (f) { return _this.emit('data', f); });
|
||||||
}));
|
}));
|
||||||
return event_stream_1.duplex(input, output);
|
return event_stream_1.duplex(input, output);
|
||||||
}
|
}
|
||||||
function isImportNode(node) {
|
function isImportNode(node) {
|
||||||
return node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */;
|
return node.kind === 212 /* ImportDeclaration */ || node.kind === 211 /* ImportEqualsDeclaration */;
|
||||||
}
|
}
|
||||||
(function (nls_1) {
|
(function (nls_1) {
|
||||||
function fileFrom(file, contents, path) {
|
function fileFrom(file, contents, path) {
|
||||||
if (path === void 0) { path = file.path; }
|
if (path === void 0) { path = file.path; }
|
||||||
return new File({
|
return new File({
|
||||||
contents: new Buffer(contents),
|
contents: new Buffer(contents),
|
||||||
base: file.base,
|
base: file.base,
|
||||||
cwd: file.cwd,
|
cwd: file.cwd,
|
||||||
path: path
|
path: path
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
nls_1.fileFrom = fileFrom;
|
nls_1.fileFrom = fileFrom;
|
||||||
function mappedPositionFrom(source, lc) {
|
function mappedPositionFrom(source, lc) {
|
||||||
return { source: source, line: lc.line + 1, column: lc.character };
|
return { source: source, line: lc.line + 1, column: lc.character };
|
||||||
}
|
}
|
||||||
nls_1.mappedPositionFrom = mappedPositionFrom;
|
nls_1.mappedPositionFrom = mappedPositionFrom;
|
||||||
function lcFrom(position) {
|
function lcFrom(position) {
|
||||||
return { line: position.line - 1, character: position.column };
|
return { line: position.line - 1, character: position.column };
|
||||||
}
|
}
|
||||||
nls_1.lcFrom = lcFrom;
|
nls_1.lcFrom = lcFrom;
|
||||||
var SingleFileServiceHost = (function () {
|
var SingleFileServiceHost = (function () {
|
||||||
function SingleFileServiceHost(options, filename, contents) {
|
function SingleFileServiceHost(options, filename, contents) {
|
||||||
var _this = this;
|
var _this = this;
|
||||||
this.options = options;
|
this.options = options;
|
||||||
this.filename = filename;
|
this.filename = filename;
|
||||||
this.getCompilationSettings = function () { return _this.options; };
|
this.getCompilationSettings = function () { return _this.options; };
|
||||||
this.getScriptFileNames = function () { return [_this.filename]; };
|
this.getScriptFileNames = function () { return [_this.filename]; };
|
||||||
this.getScriptVersion = function () { return '1'; };
|
this.getScriptVersion = function () { return '1'; };
|
||||||
this.getScriptSnapshot = function (name) { return name === _this.filename ? _this.file : _this.lib; };
|
this.getScriptSnapshot = function (name) { return name === _this.filename ? _this.file : _this.lib; };
|
||||||
this.getCurrentDirectory = function () { return ''; };
|
this.getCurrentDirectory = function () { return ''; };
|
||||||
this.getDefaultLibFileName = function () { return 'lib.d.ts'; };
|
this.getDefaultLibFileName = function () { return 'lib.d.ts'; };
|
||||||
this.file = ts.ScriptSnapshot.fromString(contents);
|
this.file = ts.ScriptSnapshot.fromString(contents);
|
||||||
this.lib = ts.ScriptSnapshot.fromString('');
|
this.lib = ts.ScriptSnapshot.fromString('');
|
||||||
}
|
}
|
||||||
return SingleFileServiceHost;
|
return SingleFileServiceHost;
|
||||||
}());
|
}());
|
||||||
nls_1.SingleFileServiceHost = SingleFileServiceHost;
|
nls_1.SingleFileServiceHost = SingleFileServiceHost;
|
||||||
function isCallExpressionWithinTextSpanCollectStep(textSpan, node) {
|
function isCallExpressionWithinTextSpanCollectStep(textSpan, node) {
|
||||||
if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) {
|
if (!ts.textSpanContainsTextSpan({ start: node.pos, length: node.end - node.pos }, textSpan)) {
|
||||||
return CollectStepResult.No;
|
return CollectStepResult.No;
|
||||||
}
|
}
|
||||||
return node.kind === 160 /* CallExpression */ ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse;
|
return node.kind === 160 /* CallExpression */ ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse;
|
||||||
}
|
}
|
||||||
function analyze(contents, options) {
|
function analyze(contents, options) {
|
||||||
if (options === void 0) { options = {}; }
|
if (options === void 0) { options = {}; }
|
||||||
var filename = 'file.ts';
|
var filename = 'file.ts';
|
||||||
var serviceHost = new SingleFileServiceHost(assign(clone(options), { noResolve: true }), filename, contents);
|
var serviceHost = new SingleFileServiceHost(assign(clone(options), { noResolve: true }), filename, contents);
|
||||||
var service = ts.createLanguageService(serviceHost);
|
var service = ts.createLanguageService(serviceHost);
|
||||||
var sourceFile = service.getSourceFile(filename);
|
var sourceFile = service.getSourceFile(filename);
|
||||||
// all imports
|
// all imports
|
||||||
var imports = lazy(collect(sourceFile, function (n) { return isImportNode(n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse; }));
|
var imports = lazy(collect(sourceFile, function (n) { return isImportNode(n) ? CollectStepResult.YesAndRecurse : CollectStepResult.NoAndRecurse; }));
|
||||||
// import nls = require('vs/nls');
|
// import nls = require('vs/nls');
|
||||||
var importEqualsDeclarations = imports
|
var importEqualsDeclarations = imports
|
||||||
.filter(function (n) { return n.kind === 211 /* ImportEqualsDeclaration */; })
|
.filter(function (n) { return n.kind === 211 /* ImportEqualsDeclaration */; })
|
||||||
.map(function (n) { return n; })
|
.map(function (n) { return n; })
|
||||||
.filter(function (d) { return d.moduleReference.kind === 222 /* ExternalModuleReference */; })
|
.filter(function (d) { return d.moduleReference.kind === 222 /* ExternalModuleReference */; })
|
||||||
.filter(function (d) { return d.moduleReference.expression.getText() === '\'vs/nls\''; });
|
.filter(function (d) { return d.moduleReference.expression.getText() === '\'vs/nls\''; });
|
||||||
// import ... from 'vs/nls';
|
// import ... from 'vs/nls';
|
||||||
var importDeclarations = imports
|
var importDeclarations = imports
|
||||||
.filter(function (n) { return n.kind === 212 /* ImportDeclaration */; })
|
.filter(function (n) { return n.kind === 212 /* ImportDeclaration */; })
|
||||||
.map(function (n) { return n; })
|
.map(function (n) { return n; })
|
||||||
.filter(function (d) { return d.moduleSpecifier.kind === 8 /* StringLiteral */; })
|
.filter(function (d) { return d.moduleSpecifier.kind === 8 /* StringLiteral */; })
|
||||||
.filter(function (d) { return d.moduleSpecifier.getText() === '\'vs/nls\''; })
|
.filter(function (d) { return d.moduleSpecifier.getText() === '\'vs/nls\''; })
|
||||||
.filter(function (d) { return !!d.importClause && !!d.importClause.namedBindings; });
|
.filter(function (d) { return !!d.importClause && !!d.importClause.namedBindings; });
|
||||||
var nlsExpressions = importEqualsDeclarations
|
var nlsExpressions = importEqualsDeclarations
|
||||||
.map(function (d) { return d.moduleReference.expression; })
|
.map(function (d) { return d.moduleReference.expression; })
|
||||||
.concat(importDeclarations.map(function (d) { return d.moduleSpecifier; }))
|
.concat(importDeclarations.map(function (d) { return d.moduleSpecifier; }))
|
||||||
.map(function (d) { return ({
|
.map(function (d) { return ({
|
||||||
start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()),
|
start: ts.getLineAndCharacterOfPosition(sourceFile, d.getStart()),
|
||||||
end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd())
|
end: ts.getLineAndCharacterOfPosition(sourceFile, d.getEnd())
|
||||||
}); });
|
}); });
|
||||||
// `nls.localize(...)` calls
|
// `nls.localize(...)` calls
|
||||||
var nlsLocalizeCallExpressions = importDeclarations
|
var nlsLocalizeCallExpressions = importDeclarations
|
||||||
.filter(function (d) { return d.importClause.namedBindings.kind === 214 /* NamespaceImport */; })
|
.filter(function (d) { return d.importClause.namedBindings.kind === 214 /* NamespaceImport */; })
|
||||||
.map(function (d) { return d.importClause.namedBindings.name; })
|
.map(function (d) { return d.importClause.namedBindings.name; })
|
||||||
.concat(importEqualsDeclarations.map(function (d) { return d.name; }))
|
.concat(importEqualsDeclarations.map(function (d) { return d.name; }))
|
||||||
.map(function (n) { return service.getReferencesAtPosition(filename, n.pos + 1); })
|
.map(function (n) { return service.getReferencesAtPosition(filename, n.pos + 1); })
|
||||||
.flatten()
|
.flatten()
|
||||||
.filter(function (r) { return !r.isWriteAccess; })
|
.filter(function (r) { return !r.isWriteAccess; })
|
||||||
.map(function (r) { return collect(sourceFile, function (n) { return isCallExpressionWithinTextSpanCollectStep(r.textSpan, n); }); })
|
.map(function (r) { return collect(sourceFile, function (n) { return isCallExpressionWithinTextSpanCollectStep(r.textSpan, n); }); })
|
||||||
.map(function (a) { return lazy(a).last(); })
|
.map(function (a) { return lazy(a).last(); })
|
||||||
.filter(function (n) { return !!n; })
|
.filter(function (n) { return !!n; })
|
||||||
.map(function (n) { return n; })
|
.map(function (n) { return n; })
|
||||||
.filter(function (n) { return n.expression.kind === 158 /* PropertyAccessExpression */ && n.expression.name.getText() === 'localize'; });
|
.filter(function (n) { return n.expression.kind === 158 /* PropertyAccessExpression */ && n.expression.name.getText() === 'localize'; });
|
||||||
// `localize` named imports
|
// `localize` named imports
|
||||||
var allLocalizeImportDeclarations = importDeclarations
|
var allLocalizeImportDeclarations = importDeclarations
|
||||||
.filter(function (d) { return d.importClause.namedBindings.kind === 215 /* NamedImports */; })
|
.filter(function (d) { return d.importClause.namedBindings.kind === 215 /* NamedImports */; })
|
||||||
.map(function (d) { return d.importClause.namedBindings.elements; })
|
.map(function (d) { return d.importClause.namedBindings.elements; })
|
||||||
.flatten();
|
.flatten();
|
||||||
// `localize` read-only references
|
// `localize` read-only references
|
||||||
var localizeReferences = allLocalizeImportDeclarations
|
var localizeReferences = allLocalizeImportDeclarations
|
||||||
.filter(function (d) { return d.name.getText() === 'localize'; })
|
.filter(function (d) { return d.name.getText() === 'localize'; })
|
||||||
.map(function (n) { return service.getReferencesAtPosition(filename, n.pos + 1); })
|
.map(function (n) { return service.getReferencesAtPosition(filename, n.pos + 1); })
|
||||||
.flatten()
|
.flatten()
|
||||||
.filter(function (r) { return !r.isWriteAccess; });
|
.filter(function (r) { return !r.isWriteAccess; });
|
||||||
// custom named `localize` read-only references
|
// custom named `localize` read-only references
|
||||||
var namedLocalizeReferences = allLocalizeImportDeclarations
|
var namedLocalizeReferences = allLocalizeImportDeclarations
|
||||||
.filter(function (d) { return d.propertyName && d.propertyName.getText() === 'localize'; })
|
.filter(function (d) { return d.propertyName && d.propertyName.getText() === 'localize'; })
|
||||||
.map(function (n) { return service.getReferencesAtPosition(filename, n.name.pos + 1); })
|
.map(function (n) { return service.getReferencesAtPosition(filename, n.name.pos + 1); })
|
||||||
.flatten()
|
.flatten()
|
||||||
.filter(function (r) { return !r.isWriteAccess; });
|
.filter(function (r) { return !r.isWriteAccess; });
|
||||||
// find the deepest call expressions AST nodes that contain those references
|
// find the deepest call expressions AST nodes that contain those references
|
||||||
var localizeCallExpressions = localizeReferences
|
var localizeCallExpressions = localizeReferences
|
||||||
.concat(namedLocalizeReferences)
|
.concat(namedLocalizeReferences)
|
||||||
.map(function (r) { return collect(sourceFile, function (n) { return isCallExpressionWithinTextSpanCollectStep(r.textSpan, n); }); })
|
.map(function (r) { return collect(sourceFile, function (n) { return isCallExpressionWithinTextSpanCollectStep(r.textSpan, n); }); })
|
||||||
.map(function (a) { return lazy(a).last(); })
|
.map(function (a) { return lazy(a).last(); })
|
||||||
.filter(function (n) { return !!n; })
|
.filter(function (n) { return !!n; })
|
||||||
.map(function (n) { return n; });
|
.map(function (n) { return n; });
|
||||||
// collect everything
|
// collect everything
|
||||||
var localizeCalls = nlsLocalizeCallExpressions
|
var localizeCalls = nlsLocalizeCallExpressions
|
||||||
.concat(localizeCallExpressions)
|
.concat(localizeCallExpressions)
|
||||||
.map(function (e) { return e.arguments; })
|
.map(function (e) { return e.arguments; })
|
||||||
.filter(function (a) { return a.length > 1; })
|
.filter(function (a) { return a.length > 1; })
|
||||||
.sort(function (a, b) { return a[0].getStart() - b[0].getStart(); })
|
.sort(function (a, b) { return a[0].getStart() - b[0].getStart(); })
|
||||||
.map(function (a) { return ({
|
.map(function (a) { return ({
|
||||||
keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) },
|
keySpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[0].getEnd()) },
|
||||||
key: a[0].getText(),
|
key: a[0].getText(),
|
||||||
valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) },
|
valueSpan: { start: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getStart()), end: ts.getLineAndCharacterOfPosition(sourceFile, a[1].getEnd()) },
|
||||||
value: a[1].getText()
|
value: a[1].getText()
|
||||||
}); });
|
}); });
|
||||||
return {
|
return {
|
||||||
localizeCalls: localizeCalls.toArray(),
|
localizeCalls: localizeCalls.toArray(),
|
||||||
nlsExpressions: nlsExpressions.toArray()
|
nlsExpressions: nlsExpressions.toArray()
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
nls_1.analyze = analyze;
|
nls_1.analyze = analyze;
|
||||||
var TextModel = (function () {
|
var TextModel = (function () {
|
||||||
function TextModel(contents) {
|
function TextModel(contents) {
|
||||||
var regex = /\r\n|\r|\n/g;
|
var regex = /\r\n|\r|\n/g;
|
||||||
var index = 0;
|
var index = 0;
|
||||||
var match;
|
var match;
|
||||||
this.lines = [];
|
this.lines = [];
|
||||||
this.lineEndings = [];
|
this.lineEndings = [];
|
||||||
while (match = regex.exec(contents)) {
|
while (match = regex.exec(contents)) {
|
||||||
this.lines.push(contents.substring(index, match.index));
|
this.lines.push(contents.substring(index, match.index));
|
||||||
this.lineEndings.push(match[0]);
|
this.lineEndings.push(match[0]);
|
||||||
index = regex.lastIndex;
|
index = regex.lastIndex;
|
||||||
}
|
}
|
||||||
if (contents.length > 0) {
|
if (contents.length > 0) {
|
||||||
this.lines.push(contents.substring(index, contents.length));
|
this.lines.push(contents.substring(index, contents.length));
|
||||||
this.lineEndings.push('');
|
this.lineEndings.push('');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
TextModel.prototype.get = function (index) {
|
TextModel.prototype.get = function (index) {
|
||||||
return this.lines[index];
|
return this.lines[index];
|
||||||
};
|
};
|
||||||
TextModel.prototype.set = function (index, line) {
|
TextModel.prototype.set = function (index, line) {
|
||||||
this.lines[index] = line;
|
this.lines[index] = line;
|
||||||
};
|
};
|
||||||
Object.defineProperty(TextModel.prototype, "lineCount", {
|
Object.defineProperty(TextModel.prototype, "lineCount", {
|
||||||
get: function () {
|
get: function () {
|
||||||
return this.lines.length;
|
return this.lines.length;
|
||||||
},
|
},
|
||||||
enumerable: true,
|
enumerable: true,
|
||||||
configurable: true
|
configurable: true
|
||||||
});
|
});
|
||||||
/**
|
/**
|
||||||
* Applies patch(es) to the model.
|
* Applies patch(es) to the model.
|
||||||
* Multiple patches must be ordered.
|
* Multiple patches must be ordered.
|
||||||
* Does not support patches spanning multiple lines.
|
* Does not support patches spanning multiple lines.
|
||||||
*/
|
*/
|
||||||
TextModel.prototype.apply = function (patch) {
|
TextModel.prototype.apply = function (patch) {
|
||||||
var startLineNumber = patch.span.start.line;
|
var startLineNumber = patch.span.start.line;
|
||||||
var endLineNumber = patch.span.end.line;
|
var endLineNumber = patch.span.end.line;
|
||||||
var startLine = this.lines[startLineNumber] || '';
|
var startLine = this.lines[startLineNumber] || '';
|
||||||
var endLine = this.lines[endLineNumber] || '';
|
var endLine = this.lines[endLineNumber] || '';
|
||||||
this.lines[startLineNumber] = [
|
this.lines[startLineNumber] = [
|
||||||
startLine.substring(0, patch.span.start.character),
|
startLine.substring(0, patch.span.start.character),
|
||||||
patch.content,
|
patch.content,
|
||||||
endLine.substring(patch.span.end.character)
|
endLine.substring(patch.span.end.character)
|
||||||
].join('');
|
].join('');
|
||||||
for (var i = startLineNumber + 1; i <= endLineNumber; i++) {
|
for (var i = startLineNumber + 1; i <= endLineNumber; i++) {
|
||||||
this.lines[i] = '';
|
this.lines[i] = '';
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
TextModel.prototype.toString = function () {
|
TextModel.prototype.toString = function () {
|
||||||
return lazy(this.lines).zip(this.lineEndings)
|
return lazy(this.lines).zip(this.lineEndings)
|
||||||
.flatten().toArray().join('');
|
.flatten().toArray().join('');
|
||||||
};
|
};
|
||||||
return TextModel;
|
return TextModel;
|
||||||
}());
|
}());
|
||||||
nls_1.TextModel = TextModel;
|
nls_1.TextModel = TextModel;
|
||||||
function patchJavascript(patches, contents, moduleId) {
|
function patchJavascript(patches, contents, moduleId) {
|
||||||
var model = new nls.TextModel(contents);
|
var model = new nls.TextModel(contents);
|
||||||
// patch the localize calls
|
// patch the localize calls
|
||||||
lazy(patches).reverse().each(function (p) { return model.apply(p); });
|
lazy(patches).reverse().each(function (p) { return model.apply(p); });
|
||||||
// patch the 'vs/nls' imports
|
// patch the 'vs/nls' imports
|
||||||
var firstLine = model.get(0);
|
var firstLine = model.get(0);
|
||||||
var patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, "$1vs/nls!" + moduleId + "$1");
|
var patchedFirstLine = firstLine.replace(/(['"])vs\/nls\1/g, "$1vs/nls!" + moduleId + "$1");
|
||||||
model.set(0, patchedFirstLine);
|
model.set(0, patchedFirstLine);
|
||||||
return model.toString();
|
return model.toString();
|
||||||
}
|
}
|
||||||
nls_1.patchJavascript = patchJavascript;
|
nls_1.patchJavascript = patchJavascript;
|
||||||
function patchSourcemap(patches, rsm, smc) {
|
function patchSourcemap(patches, rsm, smc) {
|
||||||
var smg = new sm.SourceMapGenerator({
|
var smg = new sm.SourceMapGenerator({
|
||||||
file: rsm.file,
|
file: rsm.file,
|
||||||
sourceRoot: rsm.sourceRoot
|
sourceRoot: rsm.sourceRoot
|
||||||
});
|
});
|
||||||
patches = patches.reverse();
|
patches = patches.reverse();
|
||||||
var currentLine = -1;
|
var currentLine = -1;
|
||||||
var currentLineDiff = 0;
|
var currentLineDiff = 0;
|
||||||
var source = null;
|
var source = null;
|
||||||
smc.eachMapping(function (m) {
|
smc.eachMapping(function (m) {
|
||||||
var patch = patches[patches.length - 1];
|
var patch = patches[patches.length - 1];
|
||||||
var original = { line: m.originalLine, column: m.originalColumn };
|
var original = { line: m.originalLine, column: m.originalColumn };
|
||||||
var generated = { line: m.generatedLine, column: m.generatedColumn };
|
var generated = { line: m.generatedLine, column: m.generatedColumn };
|
||||||
if (currentLine !== generated.line) {
|
if (currentLine !== generated.line) {
|
||||||
currentLineDiff = 0;
|
currentLineDiff = 0;
|
||||||
}
|
}
|
||||||
currentLine = generated.line;
|
currentLine = generated.line;
|
||||||
generated.column += currentLineDiff;
|
generated.column += currentLineDiff;
|
||||||
if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) {
|
if (patch && m.generatedLine - 1 === patch.span.end.line && m.generatedColumn === patch.span.end.character) {
|
||||||
var originalLength = patch.span.end.character - patch.span.start.character;
|
var originalLength = patch.span.end.character - patch.span.start.character;
|
||||||
var modifiedLength = patch.content.length;
|
var modifiedLength = patch.content.length;
|
||||||
var lengthDiff = modifiedLength - originalLength;
|
var lengthDiff = modifiedLength - originalLength;
|
||||||
currentLineDiff += lengthDiff;
|
currentLineDiff += lengthDiff;
|
||||||
generated.column += lengthDiff;
|
generated.column += lengthDiff;
|
||||||
patches.pop();
|
patches.pop();
|
||||||
}
|
}
|
||||||
source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source;
|
source = rsm.sourceRoot ? path.relative(rsm.sourceRoot, m.source) : m.source;
|
||||||
source = source.replace(/\\/g, '/');
|
source = source.replace(/\\/g, '/');
|
||||||
smg.addMapping({ source: source, name: m.name, original: original, generated: generated });
|
smg.addMapping({ source: source, name: m.name, original: original, generated: generated });
|
||||||
}, null, sm.SourceMapConsumer.GENERATED_ORDER);
|
}, null, sm.SourceMapConsumer.GENERATED_ORDER);
|
||||||
if (source) {
|
if (source) {
|
||||||
smg.setSourceContent(source, smc.sourceContentFor(source));
|
smg.setSourceContent(source, smc.sourceContentFor(source));
|
||||||
}
|
}
|
||||||
return JSON.parse(smg.toString());
|
return JSON.parse(smg.toString());
|
||||||
}
|
}
|
||||||
nls_1.patchSourcemap = patchSourcemap;
|
nls_1.patchSourcemap = patchSourcemap;
|
||||||
function patch(moduleId, typescript, javascript, sourcemap) {
|
function patch(moduleId, typescript, javascript, sourcemap) {
|
||||||
var _a = analyze(typescript), localizeCalls = _a.localizeCalls, nlsExpressions = _a.nlsExpressions;
|
var _a = analyze(typescript), localizeCalls = _a.localizeCalls, nlsExpressions = _a.nlsExpressions;
|
||||||
if (localizeCalls.length === 0) {
|
if (localizeCalls.length === 0) {
|
||||||
return { javascript: javascript, sourcemap: sourcemap };
|
return { javascript: javascript, sourcemap: sourcemap };
|
||||||
}
|
}
|
||||||
var nlsKeys = template(localizeCalls.map(function (lc) { return lc.key; }));
|
var nlsKeys = template(localizeCalls.map(function (lc) { return lc.key; }));
|
||||||
var nls = template(localizeCalls.map(function (lc) { return lc.value; }));
|
var nls = template(localizeCalls.map(function (lc) { return lc.value; }));
|
||||||
var smc = new sm.SourceMapConsumer(sourcemap);
|
var smc = new sm.SourceMapConsumer(sourcemap);
|
||||||
var positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]);
|
var positionFrom = mappedPositionFrom.bind(null, sourcemap.sources[0]);
|
||||||
var i = 0;
|
var i = 0;
|
||||||
// build patches
|
// build patches
|
||||||
var patches = lazy(localizeCalls)
|
var patches = lazy(localizeCalls)
|
||||||
.map(function (lc) { return ([
|
.map(function (lc) { return ([
|
||||||
{ range: lc.keySpan, content: '' + (i++) },
|
{ range: lc.keySpan, content: '' + (i++) },
|
||||||
{ range: lc.valueSpan, content: 'null' }
|
{ range: lc.valueSpan, content: 'null' }
|
||||||
]); })
|
]); })
|
||||||
.flatten()
|
.flatten()
|
||||||
.map(function (c) {
|
.map(function (c) {
|
||||||
var start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start)));
|
var start = lcFrom(smc.generatedPositionFor(positionFrom(c.range.start)));
|
||||||
var end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end)));
|
var end = lcFrom(smc.generatedPositionFor(positionFrom(c.range.end)));
|
||||||
return { span: { start: start, end: end }, content: c.content };
|
return { span: { start: start, end: end }, content: c.content };
|
||||||
})
|
})
|
||||||
.toArray();
|
.toArray();
|
||||||
javascript = patchJavascript(patches, javascript, moduleId);
|
javascript = patchJavascript(patches, javascript, moduleId);
|
||||||
// since imports are not within the sourcemap information,
|
// since imports are not within the sourcemap information,
|
||||||
// we must do this MacGyver style
|
// we must do this MacGyver style
|
||||||
if (nlsExpressions.length) {
|
if (nlsExpressions.length) {
|
||||||
javascript = javascript.replace(/^define\(.*$/m, function (line) {
|
javascript = javascript.replace(/^define\(.*$/m, function (line) {
|
||||||
return line.replace(/(['"])vs\/nls\1/g, "$1vs/nls!" + moduleId + "$1");
|
return line.replace(/(['"])vs\/nls\1/g, "$1vs/nls!" + moduleId + "$1");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
sourcemap = patchSourcemap(patches, sourcemap, smc);
|
sourcemap = patchSourcemap(patches, sourcemap, smc);
|
||||||
return { javascript: javascript, sourcemap: sourcemap, nlsKeys: nlsKeys, nls: nls };
|
return { javascript: javascript, sourcemap: sourcemap, nlsKeys: nlsKeys, nls: nls };
|
||||||
}
|
}
|
||||||
nls_1.patch = patch;
|
nls_1.patch = patch;
|
||||||
function patchFiles(javascriptFile, typescript) {
|
function patchFiles(javascriptFile, typescript) {
|
||||||
// hack?
|
// hack?
|
||||||
var moduleId = javascriptFile.relative
|
var moduleId = javascriptFile.relative
|
||||||
.replace(/\.js$/, '')
|
.replace(/\.js$/, '')
|
||||||
.replace(/\\/g, '/');
|
.replace(/\\/g, '/');
|
||||||
var _a = patch(moduleId, typescript, javascriptFile.contents.toString(), javascriptFile.sourceMap), javascript = _a.javascript, sourcemap = _a.sourcemap, nlsKeys = _a.nlsKeys, nls = _a.nls;
|
var _a = patch(moduleId, typescript, javascriptFile.contents.toString(), javascriptFile.sourceMap), javascript = _a.javascript, sourcemap = _a.sourcemap, nlsKeys = _a.nlsKeys, nls = _a.nls;
|
||||||
var result = [fileFrom(javascriptFile, javascript)];
|
var result = [fileFrom(javascriptFile, javascript)];
|
||||||
result[0].sourceMap = sourcemap;
|
result[0].sourceMap = sourcemap;
|
||||||
if (nlsKeys) {
|
if (nlsKeys) {
|
||||||
result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js')));
|
result.push(fileFrom(javascriptFile, nlsKeys, javascriptFile.path.replace(/\.js$/, '.nls.keys.js')));
|
||||||
}
|
}
|
||||||
if (nls) {
|
if (nls) {
|
||||||
result.push(fileFrom(javascriptFile, nls, javascriptFile.path.replace(/\.js$/, '.nls.js')));
|
result.push(fileFrom(javascriptFile, nls, javascriptFile.path.replace(/\.js$/, '.nls.js')));
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
nls_1.patchFiles = patchFiles;
|
nls_1.patchFiles = patchFiles;
|
||||||
})(nls || (nls = {}));
|
})(nls || (nls = {}));
|
||||||
module.exports = nls;
|
module.exports = nls;
|
||||||
|
|||||||
@@ -1,230 +1,229 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var path = require("path");
|
||||||
var path = require("path");
|
var gulp = require("gulp");
|
||||||
var gulp = require("gulp");
|
var sourcemaps = require("gulp-sourcemaps");
|
||||||
var sourcemaps = require("gulp-sourcemaps");
|
var filter = require("gulp-filter");
|
||||||
var filter = require("gulp-filter");
|
var minifyCSS = require("gulp-cssnano");
|
||||||
var minifyCSS = require("gulp-cssnano");
|
var uglify = require("gulp-uglify");
|
||||||
var uglify = require("gulp-uglify");
|
var es = require("event-stream");
|
||||||
var es = require("event-stream");
|
var concat = require("gulp-concat");
|
||||||
var concat = require("gulp-concat");
|
var VinylFile = require("vinyl");
|
||||||
var VinylFile = require("vinyl");
|
var bundle = require("./bundle");
|
||||||
var bundle = require("./bundle");
|
var util = require("./util");
|
||||||
var util = require("./util");
|
var i18n = require("./i18n");
|
||||||
var i18n = require("./i18n");
|
var gulpUtil = require("gulp-util");
|
||||||
var gulpUtil = require("gulp-util");
|
var flatmap = require("gulp-flatmap");
|
||||||
var flatmap = require("gulp-flatmap");
|
var pump = require("pump");
|
||||||
var pump = require("pump");
|
var REPO_ROOT_PATH = path.join(__dirname, '../..');
|
||||||
var REPO_ROOT_PATH = path.join(__dirname, '../..');
|
function log(prefix, message) {
|
||||||
function log(prefix, message) {
|
gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
|
||||||
gulpUtil.log(gulpUtil.colors.cyan('[' + prefix + ']'), message);
|
}
|
||||||
}
|
function loaderConfig(emptyPaths) {
|
||||||
function loaderConfig(emptyPaths) {
|
var result = {
|
||||||
var result = {
|
paths: {
|
||||||
paths: {
|
'vs': 'out-build/vs',
|
||||||
'vs': 'out-build/vs',
|
'vscode': 'empty:'
|
||||||
'vscode': 'empty:'
|
},
|
||||||
},
|
nodeModules: emptyPaths || []
|
||||||
nodeModules: emptyPaths || []
|
};
|
||||||
};
|
result['vs/css'] = { inlineResources: true };
|
||||||
result['vs/css'] = { inlineResources: true };
|
return result;
|
||||||
return result;
|
}
|
||||||
}
|
exports.loaderConfig = loaderConfig;
|
||||||
exports.loaderConfig = loaderConfig;
|
var IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
|
||||||
var IS_OUR_COPYRIGHT_REGEXP = /Copyright \(C\) Microsoft Corporation/i;
|
function loader(bundledFileHeader, bundleLoader) {
|
||||||
function loader(bundledFileHeader, bundleLoader) {
|
var sources = [
|
||||||
var sources = [
|
'out-build/vs/loader.js'
|
||||||
'out-build/vs/loader.js'
|
];
|
||||||
];
|
if (bundleLoader) {
|
||||||
if (bundleLoader) {
|
sources = sources.concat([
|
||||||
sources = sources.concat([
|
'out-build/vs/css.js',
|
||||||
'out-build/vs/css.js',
|
'out-build/vs/nls.js'
|
||||||
'out-build/vs/nls.js'
|
]);
|
||||||
]);
|
}
|
||||||
}
|
var isFirst = true;
|
||||||
var isFirst = true;
|
return (gulp
|
||||||
return (gulp
|
.src(sources, { base: 'out-build' })
|
||||||
.src(sources, { base: 'out-build' })
|
.pipe(es.through(function (data) {
|
||||||
.pipe(es.through(function (data) {
|
if (isFirst) {
|
||||||
if (isFirst) {
|
isFirst = false;
|
||||||
isFirst = false;
|
this.emit('data', new VinylFile({
|
||||||
this.emit('data', new VinylFile({
|
path: 'fake',
|
||||||
path: 'fake',
|
base: '',
|
||||||
base: '',
|
contents: new Buffer(bundledFileHeader)
|
||||||
contents: new Buffer(bundledFileHeader)
|
}));
|
||||||
}));
|
this.emit('data', data);
|
||||||
this.emit('data', data);
|
}
|
||||||
}
|
else {
|
||||||
else {
|
this.emit('data', data);
|
||||||
this.emit('data', data);
|
}
|
||||||
}
|
}))
|
||||||
}))
|
.pipe(util.loadSourcemaps())
|
||||||
.pipe(util.loadSourcemaps())
|
.pipe(concat('vs/loader.js'))
|
||||||
.pipe(concat('vs/loader.js'))
|
.pipe(es.mapSync(function (f) {
|
||||||
.pipe(es.mapSync(function (f) {
|
f.sourceMap.sourceRoot = util.toFileUri(path.join(REPO_ROOT_PATH, 'src'));
|
||||||
f.sourceMap.sourceRoot = util.toFileUri(path.join(REPO_ROOT_PATH, 'src'));
|
return f;
|
||||||
return f;
|
})));
|
||||||
})));
|
}
|
||||||
}
|
function toConcatStream(bundledFileHeader, sources, dest) {
|
||||||
function toConcatStream(bundledFileHeader, sources, dest) {
|
var useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
|
||||||
var useSourcemaps = /\.js$/.test(dest) && !/\.nls\.js$/.test(dest);
|
// If a bundle ends up including in any of the sources our copyright, then
|
||||||
// If a bundle ends up including in any of the sources our copyright, then
|
// insert a fake source at the beginning of each bundle with our copyright
|
||||||
// insert a fake source at the beginning of each bundle with our copyright
|
var containsOurCopyright = false;
|
||||||
var containsOurCopyright = false;
|
for (var i = 0, len = sources.length; i < len; i++) {
|
||||||
for (var i = 0, len = sources.length; i < len; i++) {
|
var fileContents = sources[i].contents;
|
||||||
var fileContents = sources[i].contents;
|
if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
|
||||||
if (IS_OUR_COPYRIGHT_REGEXP.test(fileContents)) {
|
containsOurCopyright = true;
|
||||||
containsOurCopyright = true;
|
break;
|
||||||
break;
|
}
|
||||||
}
|
}
|
||||||
}
|
if (containsOurCopyright) {
|
||||||
if (containsOurCopyright) {
|
sources.unshift({
|
||||||
sources.unshift({
|
path: null,
|
||||||
path: null,
|
contents: bundledFileHeader
|
||||||
contents: bundledFileHeader
|
});
|
||||||
});
|
}
|
||||||
}
|
var treatedSources = sources.map(function (source) {
|
||||||
var treatedSources = sources.map(function (source) {
|
var root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
|
||||||
var root = source.path ? REPO_ROOT_PATH.replace(/\\/g, '/') : '';
|
var base = source.path ? root + '/out-build' : '';
|
||||||
var base = source.path ? root + '/out-build' : '';
|
return new VinylFile({
|
||||||
return new VinylFile({
|
path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake',
|
||||||
path: source.path ? root + '/' + source.path.replace(/\\/g, '/') : 'fake',
|
base: base,
|
||||||
base: base,
|
contents: new Buffer(source.contents)
|
||||||
contents: new Buffer(source.contents)
|
});
|
||||||
});
|
});
|
||||||
});
|
return es.readArray(treatedSources)
|
||||||
return es.readArray(treatedSources)
|
.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
|
||||||
.pipe(useSourcemaps ? util.loadSourcemaps() : es.through())
|
.pipe(concat(dest));
|
||||||
.pipe(concat(dest));
|
}
|
||||||
}
|
function toBundleStream(bundledFileHeader, bundles) {
|
||||||
function toBundleStream(bundledFileHeader, bundles) {
|
return es.merge(bundles.map(function (bundle) {
|
||||||
return es.merge(bundles.map(function (bundle) {
|
return toConcatStream(bundledFileHeader, bundle.sources, bundle.dest);
|
||||||
return toConcatStream(bundledFileHeader, bundle.sources, bundle.dest);
|
}));
|
||||||
}));
|
}
|
||||||
}
|
function optimizeTask(opts) {
|
||||||
function optimizeTask(opts) {
|
var entryPoints = opts.entryPoints;
|
||||||
var entryPoints = opts.entryPoints;
|
var otherSources = opts.otherSources;
|
||||||
var otherSources = opts.otherSources;
|
var resources = opts.resources;
|
||||||
var resources = opts.resources;
|
var loaderConfig = opts.loaderConfig;
|
||||||
var loaderConfig = opts.loaderConfig;
|
var bundledFileHeader = opts.header;
|
||||||
var bundledFileHeader = opts.header;
|
var bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader);
|
||||||
var bundleLoader = (typeof opts.bundleLoader === 'undefined' ? true : opts.bundleLoader);
|
var out = opts.out;
|
||||||
var out = opts.out;
|
return function () {
|
||||||
return function () {
|
var bundlesStream = es.through(); // this stream will contain the bundled files
|
||||||
var bundlesStream = es.through(); // this stream will contain the bundled files
|
var resourcesStream = es.through(); // this stream will contain the resources
|
||||||
var resourcesStream = es.through(); // this stream will contain the resources
|
var bundleInfoStream = es.through(); // this stream will contain bundleInfo.json
|
||||||
var bundleInfoStream = es.through(); // this stream will contain bundleInfo.json
|
bundle.bundle(entryPoints, loaderConfig, function (err, result) {
|
||||||
bundle.bundle(entryPoints, loaderConfig, function (err, result) {
|
if (err) {
|
||||||
if (err) {
|
return bundlesStream.emit('error', JSON.stringify(err));
|
||||||
return bundlesStream.emit('error', JSON.stringify(err));
|
}
|
||||||
}
|
toBundleStream(bundledFileHeader, result.files).pipe(bundlesStream);
|
||||||
toBundleStream(bundledFileHeader, result.files).pipe(bundlesStream);
|
// Remove css inlined resources
|
||||||
// Remove css inlined resources
|
var filteredResources = resources.slice();
|
||||||
var filteredResources = resources.slice();
|
result.cssInlinedResources.forEach(function (resource) {
|
||||||
result.cssInlinedResources.forEach(function (resource) {
|
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
||||||
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
log('optimizer', 'excluding inlined: ' + resource);
|
||||||
log('optimizer', 'excluding inlined: ' + resource);
|
}
|
||||||
}
|
filteredResources.push('!' + resource);
|
||||||
filteredResources.push('!' + resource);
|
});
|
||||||
});
|
gulp.src(filteredResources, { base: 'out-build' }).pipe(resourcesStream);
|
||||||
gulp.src(filteredResources, { base: 'out-build' }).pipe(resourcesStream);
|
var bundleInfoArray = [];
|
||||||
var bundleInfoArray = [];
|
if (opts.bundleInfo) {
|
||||||
if (opts.bundleInfo) {
|
bundleInfoArray.push(new VinylFile({
|
||||||
bundleInfoArray.push(new VinylFile({
|
path: 'bundleInfo.json',
|
||||||
path: 'bundleInfo.json',
|
base: '.',
|
||||||
base: '.',
|
contents: new Buffer(JSON.stringify(result.bundleData, null, '\t'))
|
||||||
contents: new Buffer(JSON.stringify(result.bundleData, null, '\t'))
|
}));
|
||||||
}));
|
}
|
||||||
}
|
es.readArray(bundleInfoArray).pipe(bundleInfoStream);
|
||||||
es.readArray(bundleInfoArray).pipe(bundleInfoStream);
|
});
|
||||||
});
|
var otherSourcesStream = es.through();
|
||||||
var otherSourcesStream = es.through();
|
var otherSourcesStreamArr = [];
|
||||||
var otherSourcesStreamArr = [];
|
gulp.src(otherSources, { base: 'out-build' })
|
||||||
gulp.src(otherSources, { base: 'out-build' })
|
.pipe(es.through(function (data) {
|
||||||
.pipe(es.through(function (data) {
|
otherSourcesStreamArr.push(toConcatStream(bundledFileHeader, [data], data.relative));
|
||||||
otherSourcesStreamArr.push(toConcatStream(bundledFileHeader, [data], data.relative));
|
}, function () {
|
||||||
}, function () {
|
if (!otherSourcesStreamArr.length) {
|
||||||
if (!otherSourcesStreamArr.length) {
|
setTimeout(function () { otherSourcesStream.emit('end'); }, 0);
|
||||||
setTimeout(function () { otherSourcesStream.emit('end'); }, 0);
|
}
|
||||||
}
|
else {
|
||||||
else {
|
es.merge(otherSourcesStreamArr).pipe(otherSourcesStream);
|
||||||
es.merge(otherSourcesStreamArr).pipe(otherSourcesStream);
|
}
|
||||||
}
|
}));
|
||||||
}));
|
var result = es.merge(loader(bundledFileHeader, bundleLoader), bundlesStream, otherSourcesStream, resourcesStream, bundleInfoStream);
|
||||||
var result = es.merge(loader(bundledFileHeader, bundleLoader), bundlesStream, otherSourcesStream, resourcesStream, bundleInfoStream);
|
return result
|
||||||
return result
|
.pipe(sourcemaps.write('./', {
|
||||||
.pipe(sourcemaps.write('./', {
|
sourceRoot: null,
|
||||||
sourceRoot: null,
|
addComment: true,
|
||||||
addComment: true,
|
includeContent: true
|
||||||
includeContent: true
|
}))
|
||||||
}))
|
.pipe(i18n.processNlsFiles({
|
||||||
.pipe(i18n.processNlsFiles({
|
fileHeader: bundledFileHeader
|
||||||
fileHeader: bundledFileHeader
|
}))
|
||||||
}))
|
.pipe(gulp.dest(out));
|
||||||
.pipe(gulp.dest(out));
|
};
|
||||||
};
|
}
|
||||||
}
|
exports.optimizeTask = optimizeTask;
|
||||||
exports.optimizeTask = optimizeTask;
|
;
|
||||||
;
|
/**
|
||||||
/**
|
* Wrap around uglify and allow the preserveComments function
|
||||||
* Wrap around uglify and allow the preserveComments function
|
* to have a file "context" to include our copyright only once per file.
|
||||||
* to have a file "context" to include our copyright only once per file.
|
*/
|
||||||
*/
|
function uglifyWithCopyrights() {
|
||||||
function uglifyWithCopyrights() {
|
var preserveComments = function (f) {
|
||||||
var preserveComments = function (f) {
|
return function (node, comment) {
|
||||||
return function (node, comment) {
|
var text = comment.value;
|
||||||
var text = comment.value;
|
var type = comment.type;
|
||||||
var type = comment.type;
|
if (/@minifier_do_not_preserve/.test(text)) {
|
||||||
if (/@minifier_do_not_preserve/.test(text)) {
|
return false;
|
||||||
return false;
|
}
|
||||||
}
|
var isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
|
||||||
var isOurCopyright = IS_OUR_COPYRIGHT_REGEXP.test(text);
|
if (isOurCopyright) {
|
||||||
if (isOurCopyright) {
|
if (f.__hasOurCopyright) {
|
||||||
if (f.__hasOurCopyright) {
|
return false;
|
||||||
return false;
|
}
|
||||||
}
|
f.__hasOurCopyright = true;
|
||||||
f.__hasOurCopyright = true;
|
return true;
|
||||||
return true;
|
}
|
||||||
}
|
if ('comment2' === type) {
|
||||||
if ('comment2' === type) {
|
// check for /*!. Note that text doesn't contain leading /*
|
||||||
// check for /*!. Note that text doesn't contain leading /*
|
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
|
||||||
return (text.length > 0 && text[0] === '!') || /@preserve|license|@cc_on|copyright/i.test(text);
|
}
|
||||||
}
|
else if ('comment1' === type) {
|
||||||
else if ('comment1' === type) {
|
return /license|copyright/i.test(text);
|
||||||
return /license|copyright/i.test(text);
|
}
|
||||||
}
|
return false;
|
||||||
return false;
|
};
|
||||||
};
|
};
|
||||||
};
|
var input = es.through();
|
||||||
var input = es.through();
|
var output = input
|
||||||
var output = input
|
.pipe(flatmap(function (stream, f) {
|
||||||
.pipe(flatmap(function (stream, f) {
|
return stream
|
||||||
return stream
|
.pipe(uglify({ preserveComments: preserveComments(f) }));
|
||||||
.pipe(uglify({ preserveComments: preserveComments(f) }));
|
}));
|
||||||
}));
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
}
|
||||||
}
|
function minifyTask(src, sourceMapBaseUrl) {
|
||||||
function minifyTask(src, sourceMapBaseUrl) {
|
var sourceMappingURL = sourceMapBaseUrl && (function (f) { return sourceMapBaseUrl + "/" + f.relative + ".map"; });
|
||||||
var sourceMappingURL = sourceMapBaseUrl && (function (f) { return sourceMapBaseUrl + "/" + f.relative + ".map"; });
|
return function (cb) {
|
||||||
return function (cb) {
|
var jsFilter = filter('**/*.js', { restore: true });
|
||||||
var jsFilter = filter('**/*.js', { restore: true });
|
var cssFilter = filter('**/*.css', { restore: true });
|
||||||
var cssFilter = filter('**/*.css', { restore: true });
|
pump(gulp.src([src + '/**', '!' + src + '/**/*.map']), jsFilter, sourcemaps.init({ loadMaps: true }), uglifyWithCopyrights(), jsFilter.restore, cssFilter, minifyCSS({ reduceIdents: false }), cssFilter.restore, sourcemaps.write('./', {
|
||||||
pump(gulp.src([src + '/**', '!' + src + '/**/*.map']), jsFilter, sourcemaps.init({ loadMaps: true }), uglifyWithCopyrights(), jsFilter.restore, cssFilter, minifyCSS({ reduceIdents: false }), cssFilter.restore, sourcemaps.write('./', {
|
sourceMappingURL: sourceMappingURL,
|
||||||
sourceMappingURL: sourceMappingURL,
|
sourceRoot: null,
|
||||||
sourceRoot: null,
|
includeContent: true,
|
||||||
includeContent: true,
|
addComment: true
|
||||||
addComment: true
|
}), gulp.dest(src + '-min'), function (err) {
|
||||||
}), gulp.dest(src + '-min'), function (err) {
|
if (err instanceof uglify.GulpUglifyError) {
|
||||||
if (err instanceof uglify.GulpUglifyError) {
|
console.error("Uglify error in '" + (err.cause && err.cause.filename) + "'");
|
||||||
console.error("Uglify error in '" + (err.cause && err.cause.filename) + "'");
|
}
|
||||||
}
|
cb(err);
|
||||||
cb(err);
|
});
|
||||||
});
|
};
|
||||||
};
|
}
|
||||||
}
|
exports.minifyTask = minifyTask;
|
||||||
exports.minifyTask = minifyTask;
|
;
|
||||||
;
|
|
||||||
|
|||||||
@@ -1,83 +1,80 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var es = require("event-stream");
|
||||||
var es = require("event-stream");
|
var _ = require("underscore");
|
||||||
var _ = require("underscore");
|
var util = require("gulp-util");
|
||||||
var util = require("gulp-util");
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
var path = require("path");
|
||||||
var path = require("path");
|
var allErrors = [];
|
||||||
var allErrors = [];
|
var startTime = null;
|
||||||
var startTime = null;
|
var count = 0;
|
||||||
var count = 0;
|
function onStart() {
|
||||||
function onStart() {
|
if (count++ > 0) {
|
||||||
if (count++ > 0) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
startTime = new Date().getTime();
|
||||||
startTime = new Date().getTime();
|
util.log("Starting " + util.colors.green('compilation') + "...");
|
||||||
util.log("Starting " + util.colors.green('compilation') + "...");
|
}
|
||||||
}
|
function onEnd() {
|
||||||
function onEnd() {
|
if (--count > 0) {
|
||||||
if (--count > 0) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
log();
|
||||||
log();
|
}
|
||||||
}
|
var buildLogPath = path.join(path.dirname(path.dirname(__dirname)), '.build', 'log');
|
||||||
var buildLogPath = path.join(path.dirname(path.dirname(__dirname)), '.build', 'log');
|
try {
|
||||||
try {
|
fs.mkdirSync(path.dirname(buildLogPath));
|
||||||
fs.mkdirSync(path.dirname(buildLogPath));
|
}
|
||||||
}
|
catch (err) {
|
||||||
catch (err) {
|
}
|
||||||
// ignore
|
function log() {
|
||||||
}
|
var errors = _.flatten(allErrors);
|
||||||
function log() {
|
errors.map(function (err) { return util.log(util.colors.red('Error') + ": " + err); });
|
||||||
var errors = _.flatten(allErrors);
|
var regex = /^([^(]+)\((\d+),(\d+)\): (.*)$/;
|
||||||
errors.map(function (err) { return util.log(util.colors.red('Error') + ": " + err); });
|
var messages = errors
|
||||||
var regex = /^([^(]+)\((\d+),(\d+)\): (.*)$/;
|
.map(function (err) { return regex.exec(err); })
|
||||||
var messages = errors
|
.filter(function (match) { return !!match; })
|
||||||
.map(function (err) { return regex.exec(err); })
|
.map(function (_a) {
|
||||||
.filter(function (match) { return !!match; })
|
var path = _a[1], line = _a[2], column = _a[3], message = _a[4];
|
||||||
.map(function (_a) {
|
return ({ path: path, line: Number.parseInt(line), column: Number.parseInt(column), message: message });
|
||||||
var path = _a[1], line = _a[2], column = _a[3], message = _a[4];
|
});
|
||||||
return ({ path: path, line: Number.parseInt(line), column: Number.parseInt(column), message: message });
|
try {
|
||||||
});
|
fs.writeFileSync(buildLogPath, JSON.stringify(messages));
|
||||||
try {
|
}
|
||||||
fs.writeFileSync(buildLogPath, JSON.stringify(messages));
|
catch (err) {
|
||||||
}
|
}
|
||||||
catch (err) {
|
util.log("Finished " + util.colors.green('compilation') + " with " + errors.length + " errors after " + util.colors.magenta((new Date().getTime() - startTime) + ' ms'));
|
||||||
//noop
|
}
|
||||||
}
|
function createReporter() {
|
||||||
util.log("Finished " + util.colors.green('compilation') + " with " + errors.length + " errors after " + util.colors.magenta((new Date().getTime() - startTime) + ' ms'));
|
var errors = [];
|
||||||
}
|
allErrors.push(errors);
|
||||||
function createReporter() {
|
var ReportFunc = (function () {
|
||||||
var errors = [];
|
function ReportFunc(err) {
|
||||||
allErrors.push(errors);
|
errors.push(err);
|
||||||
var ReportFunc = (function () {
|
}
|
||||||
function ReportFunc(err) {
|
ReportFunc.hasErrors = function () {
|
||||||
errors.push(err);
|
return errors.length > 0;
|
||||||
}
|
};
|
||||||
ReportFunc.hasErrors = function () {
|
ReportFunc.end = function (emitError) {
|
||||||
return errors.length > 0;
|
errors.length = 0;
|
||||||
};
|
onStart();
|
||||||
ReportFunc.end = function (emitError) {
|
return es.through(null, function () {
|
||||||
errors.length = 0;
|
onEnd();
|
||||||
onStart();
|
if (emitError && errors.length > 0) {
|
||||||
return es.through(null, function () {
|
log();
|
||||||
onEnd();
|
this.emit('error');
|
||||||
if (emitError && errors.length > 0) {
|
}
|
||||||
log();
|
else {
|
||||||
this.emit('error');
|
this.emit('end');
|
||||||
}
|
}
|
||||||
else {
|
});
|
||||||
this.emit('end');
|
};
|
||||||
}
|
return ReportFunc;
|
||||||
});
|
}());
|
||||||
};
|
return ReportFunc;
|
||||||
return ReportFunc;
|
}
|
||||||
}());
|
exports.createReporter = createReporter;
|
||||||
return ReportFunc;
|
;
|
||||||
}
|
|
||||||
exports.createReporter = createReporter;
|
|
||||||
;
|
|
||||||
|
|||||||
@@ -1,50 +1,44 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
var __extends = (this && this.__extends) || (function () {
|
var __extends = (this && this.__extends) || function (d, b) {
|
||||||
var extendStatics = Object.setPrototypeOf ||
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
||||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
function __() { this.constructor = d; }
|
||||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||||
return function (d, b) {
|
};
|
||||||
extendStatics(d, b);
|
var path_1 = require("path");
|
||||||
function __() { this.constructor = d; }
|
var Lint = require("tslint");
|
||||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
var Rule = (function (_super) {
|
||||||
};
|
__extends(Rule, _super);
|
||||||
})();
|
function Rule() {
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
return _super !== null && _super.apply(this, arguments) || this;
|
||||||
var path_1 = require("path");
|
}
|
||||||
var Lint = require("tslint");
|
Rule.prototype.apply = function (sourceFile) {
|
||||||
var Rule = (function (_super) {
|
return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions()));
|
||||||
__extends(Rule, _super);
|
};
|
||||||
function Rule() {
|
return Rule;
|
||||||
return _super !== null && _super.apply(this, arguments) || this;
|
}(Lint.Rules.AbstractRule));
|
||||||
}
|
exports.Rule = Rule;
|
||||||
Rule.prototype.apply = function (sourceFile) {
|
var ImportPatterns = (function (_super) {
|
||||||
return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions()));
|
__extends(ImportPatterns, _super);
|
||||||
};
|
function ImportPatterns(file, opts) {
|
||||||
return Rule;
|
var _this = _super.call(this, file, opts) || this;
|
||||||
}(Lint.Rules.AbstractRule));
|
_this.imports = Object.create(null);
|
||||||
exports.Rule = Rule;
|
return _this;
|
||||||
var ImportPatterns = (function (_super) {
|
}
|
||||||
__extends(ImportPatterns, _super);
|
ImportPatterns.prototype.visitImportDeclaration = function (node) {
|
||||||
function ImportPatterns(file, opts) {
|
var path = node.moduleSpecifier.getText();
|
||||||
var _this = _super.call(this, file, opts) || this;
|
// remove quotes
|
||||||
_this.imports = Object.create(null);
|
path = path.slice(1, -1);
|
||||||
return _this;
|
if (path[0] === '.') {
|
||||||
}
|
path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path);
|
||||||
ImportPatterns.prototype.visitImportDeclaration = function (node) {
|
}
|
||||||
var path = node.moduleSpecifier.getText();
|
if (this.imports[path]) {
|
||||||
// remove quotes
|
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Duplicate imports for '" + path + "'."));
|
||||||
path = path.slice(1, -1);
|
}
|
||||||
if (path[0] === '.') {
|
this.imports[path] = true;
|
||||||
path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path);
|
};
|
||||||
}
|
return ImportPatterns;
|
||||||
if (this.imports[path]) {
|
}(Lint.RuleWalker));
|
||||||
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Duplicate imports for '" + path + "'."));
|
|
||||||
}
|
|
||||||
this.imports[path] = true;
|
|
||||||
};
|
|
||||||
return ImportPatterns;
|
|
||||||
}(Lint.RuleWalker));
|
|
||||||
|
|||||||
@@ -1,57 +1,51 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
var __extends = (this && this.__extends) || (function () {
|
var __extends = (this && this.__extends) || function (d, b) {
|
||||||
var extendStatics = Object.setPrototypeOf ||
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
||||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
function __() { this.constructor = d; }
|
||||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||||
return function (d, b) {
|
};
|
||||||
extendStatics(d, b);
|
var Lint = require("tslint");
|
||||||
function __() { this.constructor = d; }
|
var minimatch = require("minimatch");
|
||||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
var Rule = (function (_super) {
|
||||||
};
|
__extends(Rule, _super);
|
||||||
})();
|
function Rule() {
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
return _super !== null && _super.apply(this, arguments) || this;
|
||||||
var Lint = require("tslint");
|
}
|
||||||
var minimatch = require("minimatch");
|
Rule.prototype.apply = function (sourceFile) {
|
||||||
var Rule = (function (_super) {
|
var configs = this.getOptions().ruleArguments;
|
||||||
__extends(Rule, _super);
|
for (var _i = 0, configs_1 = configs; _i < configs_1.length; _i++) {
|
||||||
function Rule() {
|
var config = configs_1[_i];
|
||||||
return _super !== null && _super.apply(this, arguments) || this;
|
if (minimatch(sourceFile.fileName, config.target)) {
|
||||||
}
|
return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions(), config));
|
||||||
Rule.prototype.apply = function (sourceFile) {
|
}
|
||||||
var configs = this.getOptions().ruleArguments;
|
}
|
||||||
for (var _i = 0, configs_1 = configs; _i < configs_1.length; _i++) {
|
return [];
|
||||||
var config = configs_1[_i];
|
};
|
||||||
if (minimatch(sourceFile.fileName, config.target)) {
|
return Rule;
|
||||||
return this.applyWithWalker(new ImportPatterns(sourceFile, this.getOptions(), config));
|
}(Lint.Rules.AbstractRule));
|
||||||
}
|
exports.Rule = Rule;
|
||||||
}
|
var ImportPatterns = (function (_super) {
|
||||||
return [];
|
__extends(ImportPatterns, _super);
|
||||||
};
|
function ImportPatterns(file, opts, _config) {
|
||||||
return Rule;
|
var _this = _super.call(this, file, opts) || this;
|
||||||
}(Lint.Rules.AbstractRule));
|
_this._config = _config;
|
||||||
exports.Rule = Rule;
|
return _this;
|
||||||
var ImportPatterns = (function (_super) {
|
}
|
||||||
__extends(ImportPatterns, _super);
|
ImportPatterns.prototype.visitImportDeclaration = function (node) {
|
||||||
function ImportPatterns(file, opts, _config) {
|
var path = node.moduleSpecifier.getText();
|
||||||
var _this = _super.call(this, file, opts) || this;
|
// remove quotes
|
||||||
_this._config = _config;
|
path = path.slice(1, -1);
|
||||||
return _this;
|
// ignore relative paths
|
||||||
}
|
if (path[0] === '.') {
|
||||||
ImportPatterns.prototype.visitImportDeclaration = function (node) {
|
return;
|
||||||
var path = node.moduleSpecifier.getText();
|
}
|
||||||
// remove quotes
|
if (!minimatch(path, this._config.restrictions)) {
|
||||||
path = path.slice(1, -1);
|
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Imports violates '" + this._config.restrictions + "'-restriction."));
|
||||||
// ignore relative paths
|
}
|
||||||
if (path[0] === '.') {
|
};
|
||||||
return;
|
return ImportPatterns;
|
||||||
}
|
}(Lint.RuleWalker));
|
||||||
if (!minimatch(path, this._config.restrictions)) {
|
|
||||||
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Imports violates '" + this._config.restrictions + "'-restriction."));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return ImportPatterns;
|
|
||||||
}(Lint.RuleWalker));
|
|
||||||
|
|||||||
@@ -1,85 +1,79 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
var __extends = (this && this.__extends) || (function () {
|
var __extends = (this && this.__extends) || function (d, b) {
|
||||||
var extendStatics = Object.setPrototypeOf ||
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
||||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
function __() { this.constructor = d; }
|
||||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||||
return function (d, b) {
|
};
|
||||||
extendStatics(d, b);
|
var Lint = require("tslint");
|
||||||
function __() { this.constructor = d; }
|
var path_1 = require("path");
|
||||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
var Rule = (function (_super) {
|
||||||
};
|
__extends(Rule, _super);
|
||||||
})();
|
function Rule() {
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
return _super !== null && _super.apply(this, arguments) || this;
|
||||||
var Lint = require("tslint");
|
}
|
||||||
var path_1 = require("path");
|
Rule.prototype.apply = function (sourceFile) {
|
||||||
var Rule = (function (_super) {
|
var parts = path_1.dirname(sourceFile.fileName).split(/\\|\//);
|
||||||
__extends(Rule, _super);
|
var ruleArgs = this.getOptions().ruleArguments[0];
|
||||||
function Rule() {
|
var config;
|
||||||
return _super !== null && _super.apply(this, arguments) || this;
|
for (var i = parts.length - 1; i >= 0; i--) {
|
||||||
}
|
if (ruleArgs[parts[i]]) {
|
||||||
Rule.prototype.apply = function (sourceFile) {
|
config = {
|
||||||
var parts = path_1.dirname(sourceFile.fileName).split(/\\|\//);
|
allowed: new Set(ruleArgs[parts[i]]).add(parts[i]),
|
||||||
var ruleArgs = this.getOptions().ruleArguments[0];
|
disallowed: new Set()
|
||||||
var config;
|
};
|
||||||
for (var i = parts.length - 1; i >= 0; i--) {
|
Object.keys(ruleArgs).forEach(function (key) {
|
||||||
if (ruleArgs[parts[i]]) {
|
if (!config.allowed.has(key)) {
|
||||||
config = {
|
config.disallowed.add(key);
|
||||||
allowed: new Set(ruleArgs[parts[i]]).add(parts[i]),
|
}
|
||||||
disallowed: new Set()
|
});
|
||||||
};
|
break;
|
||||||
Object.keys(ruleArgs).forEach(function (key) {
|
}
|
||||||
if (!config.allowed.has(key)) {
|
}
|
||||||
config.disallowed.add(key);
|
if (!config) {
|
||||||
}
|
return [];
|
||||||
});
|
}
|
||||||
break;
|
return this.applyWithWalker(new LayeringRule(sourceFile, config, this.getOptions()));
|
||||||
}
|
};
|
||||||
}
|
return Rule;
|
||||||
if (!config) {
|
}(Lint.Rules.AbstractRule));
|
||||||
return [];
|
exports.Rule = Rule;
|
||||||
}
|
var LayeringRule = (function (_super) {
|
||||||
return this.applyWithWalker(new LayeringRule(sourceFile, config, this.getOptions()));
|
__extends(LayeringRule, _super);
|
||||||
};
|
function LayeringRule(file, config, opts) {
|
||||||
return Rule;
|
var _this = _super.call(this, file, opts) || this;
|
||||||
}(Lint.Rules.AbstractRule));
|
_this._config = config;
|
||||||
exports.Rule = Rule;
|
return _this;
|
||||||
var LayeringRule = (function (_super) {
|
}
|
||||||
__extends(LayeringRule, _super);
|
LayeringRule.prototype.visitImportDeclaration = function (node) {
|
||||||
function LayeringRule(file, config, opts) {
|
var path = node.moduleSpecifier.getText();
|
||||||
var _this = _super.call(this, file, opts) || this;
|
// remove quotes
|
||||||
_this._config = config;
|
path = path.slice(1, -1);
|
||||||
return _this;
|
if (path[0] === '.') {
|
||||||
}
|
path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path);
|
||||||
LayeringRule.prototype.visitImportDeclaration = function (node) {
|
}
|
||||||
var path = node.moduleSpecifier.getText();
|
var parts = path_1.dirname(path).split(/\\|\//);
|
||||||
// remove quotes
|
for (var i = parts.length - 1; i >= 0; i--) {
|
||||||
path = path.slice(1, -1);
|
var part = parts[i];
|
||||||
if (path[0] === '.') {
|
if (this._config.allowed.has(part)) {
|
||||||
path = path_1.join(path_1.dirname(node.getSourceFile().fileName), path);
|
// GOOD - same layer
|
||||||
}
|
return;
|
||||||
var parts = path_1.dirname(path).split(/\\|\//);
|
}
|
||||||
for (var i = parts.length - 1; i >= 0; i--) {
|
if (this._config.disallowed.has(part)) {
|
||||||
var part = parts[i];
|
// BAD - wrong layer
|
||||||
if (this._config.allowed.has(part)) {
|
var message = "Bad layering. You are not allowed to access '" + part + "' from here, allowed layers are: [" + LayeringRule._print(this._config.allowed) + "]";
|
||||||
// GOOD - same layer
|
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), message));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this._config.disallowed.has(part)) {
|
}
|
||||||
// BAD - wrong layer
|
};
|
||||||
var message = "Bad layering. You are not allowed to access '" + part + "' from here, allowed layers are: [" + LayeringRule._print(this._config.allowed) + "]";
|
LayeringRule._print = function (set) {
|
||||||
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), message));
|
var r = [];
|
||||||
return;
|
set.forEach(function (e) { return r.push(e); });
|
||||||
}
|
return r.join(', ');
|
||||||
}
|
};
|
||||||
};
|
return LayeringRule;
|
||||||
LayeringRule._print = function (set) {
|
}(Lint.RuleWalker));
|
||||||
var r = [];
|
|
||||||
set.forEach(function (e) { return r.push(e); });
|
|
||||||
return r.join(', ');
|
|
||||||
};
|
|
||||||
return LayeringRule;
|
|
||||||
}(Lint.RuleWalker));
|
|
||||||
|
|||||||
@@ -1,177 +1,171 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
var __extends = (this && this.__extends) || (function () {
|
var __extends = (this && this.__extends) || function (d, b) {
|
||||||
var extendStatics = Object.setPrototypeOf ||
|
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
|
||||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
function __() { this.constructor = d; }
|
||||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||||
return function (d, b) {
|
};
|
||||||
extendStatics(d, b);
|
var ts = require("typescript");
|
||||||
function __() { this.constructor = d; }
|
var Lint = require("tslint");
|
||||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
/**
|
||||||
};
|
* Implementation of the no-unexternalized-strings rule.
|
||||||
})();
|
*/
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var Rule = (function (_super) {
|
||||||
var ts = require("typescript");
|
__extends(Rule, _super);
|
||||||
var Lint = require("tslint");
|
function Rule() {
|
||||||
/**
|
return _super !== null && _super.apply(this, arguments) || this;
|
||||||
* Implementation of the no-unexternalized-strings rule.
|
}
|
||||||
*/
|
Rule.prototype.apply = function (sourceFile) {
|
||||||
var Rule = (function (_super) {
|
return this.applyWithWalker(new NoUnexternalizedStringsRuleWalker(sourceFile, this.getOptions()));
|
||||||
__extends(Rule, _super);
|
};
|
||||||
function Rule() {
|
return Rule;
|
||||||
return _super !== null && _super.apply(this, arguments) || this;
|
}(Lint.Rules.AbstractRule));
|
||||||
}
|
exports.Rule = Rule;
|
||||||
Rule.prototype.apply = function (sourceFile) {
|
function isStringLiteral(node) {
|
||||||
return this.applyWithWalker(new NoUnexternalizedStringsRuleWalker(sourceFile, this.getOptions()));
|
return node && node.kind === ts.SyntaxKind.StringLiteral;
|
||||||
};
|
}
|
||||||
return Rule;
|
function isObjectLiteral(node) {
|
||||||
}(Lint.Rules.AbstractRule));
|
return node && node.kind === ts.SyntaxKind.ObjectLiteralExpression;
|
||||||
exports.Rule = Rule;
|
}
|
||||||
function isStringLiteral(node) {
|
function isPropertyAssignment(node) {
|
||||||
return node && node.kind === ts.SyntaxKind.StringLiteral;
|
return node && node.kind === ts.SyntaxKind.PropertyAssignment;
|
||||||
}
|
}
|
||||||
function isObjectLiteral(node) {
|
var NoUnexternalizedStringsRuleWalker = (function (_super) {
|
||||||
return node && node.kind === ts.SyntaxKind.ObjectLiteralExpression;
|
__extends(NoUnexternalizedStringsRuleWalker, _super);
|
||||||
}
|
function NoUnexternalizedStringsRuleWalker(file, opts) {
|
||||||
function isPropertyAssignment(node) {
|
var _this = _super.call(this, file, opts) || this;
|
||||||
return node && node.kind === ts.SyntaxKind.PropertyAssignment;
|
_this.signatures = Object.create(null);
|
||||||
}
|
_this.ignores = Object.create(null);
|
||||||
var NoUnexternalizedStringsRuleWalker = (function (_super) {
|
_this.messageIndex = undefined;
|
||||||
__extends(NoUnexternalizedStringsRuleWalker, _super);
|
_this.keyIndex = undefined;
|
||||||
function NoUnexternalizedStringsRuleWalker(file, opts) {
|
_this.usedKeys = Object.create(null);
|
||||||
var _this = _super.call(this, file, opts) || this;
|
var options = _this.getOptions();
|
||||||
_this.signatures = Object.create(null);
|
var first = options && options.length > 0 ? options[0] : null;
|
||||||
_this.ignores = Object.create(null);
|
if (first) {
|
||||||
_this.messageIndex = undefined;
|
if (Array.isArray(first.signatures)) {
|
||||||
_this.keyIndex = undefined;
|
first.signatures.forEach(function (signature) { return _this.signatures[signature] = true; });
|
||||||
_this.usedKeys = Object.create(null);
|
}
|
||||||
var options = _this.getOptions();
|
if (Array.isArray(first.ignores)) {
|
||||||
var first = options && options.length > 0 ? options[0] : null;
|
first.ignores.forEach(function (ignore) { return _this.ignores[ignore] = true; });
|
||||||
if (first) {
|
}
|
||||||
if (Array.isArray(first.signatures)) {
|
if (typeof first.messageIndex !== 'undefined') {
|
||||||
first.signatures.forEach(function (signature) { return _this.signatures[signature] = true; });
|
_this.messageIndex = first.messageIndex;
|
||||||
}
|
}
|
||||||
if (Array.isArray(first.ignores)) {
|
if (typeof first.keyIndex !== 'undefined') {
|
||||||
first.ignores.forEach(function (ignore) { return _this.ignores[ignore] = true; });
|
_this.keyIndex = first.keyIndex;
|
||||||
}
|
}
|
||||||
if (typeof first.messageIndex !== 'undefined') {
|
}
|
||||||
_this.messageIndex = first.messageIndex;
|
return _this;
|
||||||
}
|
}
|
||||||
if (typeof first.keyIndex !== 'undefined') {
|
NoUnexternalizedStringsRuleWalker.prototype.visitSourceFile = function (node) {
|
||||||
_this.keyIndex = first.keyIndex;
|
var _this = this;
|
||||||
}
|
_super.prototype.visitSourceFile.call(this, node);
|
||||||
}
|
Object.keys(this.usedKeys).forEach(function (key) {
|
||||||
return _this;
|
var occurences = _this.usedKeys[key];
|
||||||
}
|
if (occurences.length > 1) {
|
||||||
NoUnexternalizedStringsRuleWalker.prototype.visitSourceFile = function (node) {
|
occurences.forEach(function (occurence) {
|
||||||
var _this = this;
|
_this.addFailure((_this.createFailure(occurence.key.getStart(), occurence.key.getWidth(), "Duplicate key " + occurence.key.getText() + " with different message value.")));
|
||||||
_super.prototype.visitSourceFile.call(this, node);
|
});
|
||||||
Object.keys(this.usedKeys).forEach(function (key) {
|
}
|
||||||
var occurences = _this.usedKeys[key];
|
});
|
||||||
if (occurences.length > 1) {
|
};
|
||||||
occurences.forEach(function (occurence) {
|
NoUnexternalizedStringsRuleWalker.prototype.visitStringLiteral = function (node) {
|
||||||
_this.addFailure((_this.createFailure(occurence.key.getStart(), occurence.key.getWidth(), "Duplicate key " + occurence.key.getText() + " with different message value.")));
|
this.checkStringLiteral(node);
|
||||||
});
|
_super.prototype.visitStringLiteral.call(this, node);
|
||||||
}
|
};
|
||||||
});
|
NoUnexternalizedStringsRuleWalker.prototype.checkStringLiteral = function (node) {
|
||||||
};
|
var text = node.getText();
|
||||||
NoUnexternalizedStringsRuleWalker.prototype.visitStringLiteral = function (node) {
|
var doubleQuoted = text.length >= 2 && text[0] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE && text[text.length - 1] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE;
|
||||||
this.checkStringLiteral(node);
|
var info = this.findDescribingParent(node);
|
||||||
_super.prototype.visitStringLiteral.call(this, node);
|
// Ignore strings in import and export nodes.
|
||||||
};
|
if (info && info.ignoreUsage) {
|
||||||
NoUnexternalizedStringsRuleWalker.prototype.checkStringLiteral = function (node) {
|
return;
|
||||||
var text = node.getText();
|
}
|
||||||
var doubleQuoted = text.length >= 2 && text[0] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE && text[text.length - 1] === NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE;
|
var callInfo = info ? info.callInfo : null;
|
||||||
var info = this.findDescribingParent(node);
|
var functionName = callInfo ? callInfo.callExpression.expression.getText() : null;
|
||||||
// Ignore strings in import and export nodes.
|
if (functionName && this.ignores[functionName]) {
|
||||||
if (info && info.ignoreUsage) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
if (doubleQuoted && (!callInfo || callInfo.argIndex === -1 || !this.signatures[functionName])) {
|
||||||
var callInfo = info ? info.callInfo : null;
|
var s = node.getText();
|
||||||
var functionName = callInfo ? callInfo.callExpression.expression.getText() : null;
|
var replacement = new Lint.Replacement(node.getStart(), node.getWidth(), "nls.localize('KEY-" + s.substring(1, s.length - 1) + "', " + s + ")");
|
||||||
if (functionName && this.ignores[functionName]) {
|
var fix = new Lint.Fix('Unexternalitzed string', [replacement]);
|
||||||
return;
|
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Unexternalized string found: " + node.getText(), fix));
|
||||||
}
|
return;
|
||||||
if (doubleQuoted && (!callInfo || callInfo.argIndex === -1 || !this.signatures[functionName])) {
|
}
|
||||||
var s = node.getText();
|
// We have a single quoted string outside a localize function name.
|
||||||
var replacement = new Lint.Replacement(node.getStart(), node.getWidth(), "nls.localize('KEY-" + s.substring(1, s.length - 1) + "', " + s + ")");
|
if (!doubleQuoted && !this.signatures[functionName]) {
|
||||||
var fix = new Lint.Fix('Unexternalitzed string', [replacement]);
|
return;
|
||||||
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), "Unexternalized string found: " + node.getText(), fix));
|
}
|
||||||
return;
|
// We have a string that is a direct argument into the localize call.
|
||||||
}
|
var keyArg = callInfo.argIndex === this.keyIndex
|
||||||
// We have a single quoted string outside a localize function name.
|
? callInfo.callExpression.arguments[this.keyIndex]
|
||||||
if (!doubleQuoted && !this.signatures[functionName]) {
|
: null;
|
||||||
return;
|
if (keyArg) {
|
||||||
}
|
if (isStringLiteral(keyArg)) {
|
||||||
// We have a string that is a direct argument into the localize call.
|
this.recordKey(keyArg, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
|
||||||
var keyArg = callInfo.argIndex === this.keyIndex
|
}
|
||||||
? callInfo.callExpression.arguments[this.keyIndex]
|
else if (isObjectLiteral(keyArg)) {
|
||||||
: null;
|
for (var i = 0; i < keyArg.properties.length; i++) {
|
||||||
if (keyArg) {
|
var property = keyArg.properties[i];
|
||||||
if (isStringLiteral(keyArg)) {
|
if (isPropertyAssignment(property)) {
|
||||||
this.recordKey(keyArg, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
|
var name_1 = property.name.getText();
|
||||||
}
|
if (name_1 === 'key') {
|
||||||
else if (isObjectLiteral(keyArg)) {
|
var initializer = property.initializer;
|
||||||
for (var i = 0; i < keyArg.properties.length; i++) {
|
if (isStringLiteral(initializer)) {
|
||||||
var property = keyArg.properties[i];
|
this.recordKey(initializer, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
|
||||||
if (isPropertyAssignment(property)) {
|
}
|
||||||
var name_1 = property.name.getText();
|
break;
|
||||||
if (name_1 === 'key') {
|
}
|
||||||
var initializer = property.initializer;
|
}
|
||||||
if (isStringLiteral(initializer)) {
|
}
|
||||||
this.recordKey(initializer, this.messageIndex ? callInfo.callExpression.arguments[this.messageIndex] : undefined);
|
}
|
||||||
}
|
}
|
||||||
break;
|
var messageArg = callInfo.argIndex === this.messageIndex
|
||||||
}
|
? callInfo.callExpression.arguments[this.messageIndex]
|
||||||
}
|
: null;
|
||||||
}
|
if (messageArg && messageArg !== node) {
|
||||||
}
|
this.addFailure(this.createFailure(messageArg.getStart(), messageArg.getWidth(), "Message argument to '" + callInfo.callExpression.expression.getText() + "' must be a string literal."));
|
||||||
}
|
return;
|
||||||
var messageArg = callInfo.argIndex === this.messageIndex
|
}
|
||||||
? callInfo.callExpression.arguments[this.messageIndex]
|
};
|
||||||
: null;
|
NoUnexternalizedStringsRuleWalker.prototype.recordKey = function (keyNode, messageNode) {
|
||||||
if (messageArg && messageArg !== node) {
|
var text = keyNode.getText();
|
||||||
this.addFailure(this.createFailure(messageArg.getStart(), messageArg.getWidth(), "Message argument to '" + callInfo.callExpression.expression.getText() + "' must be a string literal."));
|
var occurences = this.usedKeys[text];
|
||||||
return;
|
if (!occurences) {
|
||||||
}
|
occurences = [];
|
||||||
};
|
this.usedKeys[text] = occurences;
|
||||||
NoUnexternalizedStringsRuleWalker.prototype.recordKey = function (keyNode, messageNode) {
|
}
|
||||||
var text = keyNode.getText();
|
if (messageNode) {
|
||||||
var occurences = this.usedKeys[text];
|
if (occurences.some(function (pair) { return pair.message ? pair.message.getText() === messageNode.getText() : false; })) {
|
||||||
if (!occurences) {
|
return;
|
||||||
occurences = [];
|
}
|
||||||
this.usedKeys[text] = occurences;
|
}
|
||||||
}
|
occurences.push({ key: keyNode, message: messageNode });
|
||||||
if (messageNode) {
|
};
|
||||||
if (occurences.some(function (pair) { return pair.message ? pair.message.getText() === messageNode.getText() : false; })) {
|
NoUnexternalizedStringsRuleWalker.prototype.findDescribingParent = function (node) {
|
||||||
return;
|
var parent;
|
||||||
}
|
while ((parent = node.parent)) {
|
||||||
}
|
var kind = parent.kind;
|
||||||
occurences.push({ key: keyNode, message: messageNode });
|
if (kind === ts.SyntaxKind.CallExpression) {
|
||||||
};
|
var callExpression = parent;
|
||||||
NoUnexternalizedStringsRuleWalker.prototype.findDescribingParent = function (node) {
|
return { callInfo: { callExpression: callExpression, argIndex: callExpression.arguments.indexOf(node) } };
|
||||||
var parent;
|
}
|
||||||
while ((parent = node.parent)) {
|
else if (kind === ts.SyntaxKind.ImportEqualsDeclaration || kind === ts.SyntaxKind.ImportDeclaration || kind === ts.SyntaxKind.ExportDeclaration) {
|
||||||
var kind = parent.kind;
|
return { ignoreUsage: true };
|
||||||
if (kind === ts.SyntaxKind.CallExpression) {
|
}
|
||||||
var callExpression = parent;
|
else if (kind === ts.SyntaxKind.VariableDeclaration || kind === ts.SyntaxKind.FunctionDeclaration || kind === ts.SyntaxKind.PropertyDeclaration
|
||||||
return { callInfo: { callExpression: callExpression, argIndex: callExpression.arguments.indexOf(node) } };
|
|| kind === ts.SyntaxKind.MethodDeclaration || kind === ts.SyntaxKind.VariableDeclarationList || kind === ts.SyntaxKind.InterfaceDeclaration
|
||||||
}
|
|| kind === ts.SyntaxKind.ClassDeclaration || kind === ts.SyntaxKind.EnumDeclaration || kind === ts.SyntaxKind.ModuleDeclaration
|
||||||
else if (kind === ts.SyntaxKind.ImportEqualsDeclaration || kind === ts.SyntaxKind.ImportDeclaration || kind === ts.SyntaxKind.ExportDeclaration) {
|
|| kind === ts.SyntaxKind.TypeAliasDeclaration || kind === ts.SyntaxKind.SourceFile) {
|
||||||
return { ignoreUsage: true };
|
return null;
|
||||||
}
|
}
|
||||||
else if (kind === ts.SyntaxKind.VariableDeclaration || kind === ts.SyntaxKind.FunctionDeclaration || kind === ts.SyntaxKind.PropertyDeclaration
|
node = parent;
|
||||||
|| kind === ts.SyntaxKind.MethodDeclaration || kind === ts.SyntaxKind.VariableDeclarationList || kind === ts.SyntaxKind.InterfaceDeclaration
|
}
|
||||||
|| kind === ts.SyntaxKind.ClassDeclaration || kind === ts.SyntaxKind.EnumDeclaration || kind === ts.SyntaxKind.ModuleDeclaration
|
};
|
||||||
|| kind === ts.SyntaxKind.TypeAliasDeclaration || kind === ts.SyntaxKind.SourceFile) {
|
return NoUnexternalizedStringsRuleWalker;
|
||||||
return null;
|
}(Lint.RuleWalker));
|
||||||
}
|
NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE = '"';
|
||||||
node = parent;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
return NoUnexternalizedStringsRuleWalker;
|
|
||||||
}(Lint.RuleWalker));
|
|
||||||
NoUnexternalizedStringsRuleWalker.DOUBLE_QUOTE = '"';
|
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "es5",
|
|
||||||
"lib": [
|
|
||||||
"es2015"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,213 +1,212 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
'use strict';
|
'use strict';
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var es = require("event-stream");
|
||||||
var es = require("event-stream");
|
var debounce = require("debounce");
|
||||||
var debounce = require("debounce");
|
var _filter = require("gulp-filter");
|
||||||
var _filter = require("gulp-filter");
|
var rename = require("gulp-rename");
|
||||||
var rename = require("gulp-rename");
|
var _ = require("underscore");
|
||||||
var _ = require("underscore");
|
var path = require("path");
|
||||||
var path = require("path");
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
var _rimraf = require("rimraf");
|
||||||
var _rimraf = require("rimraf");
|
var git = require("./git");
|
||||||
var git = require("./git");
|
var VinylFile = require("vinyl");
|
||||||
var VinylFile = require("vinyl");
|
var NoCancellationToken = { isCancellationRequested: function () { return false; } };
|
||||||
var NoCancellationToken = { isCancellationRequested: function () { return false; } };
|
function incremental(streamProvider, initial, supportsCancellation) {
|
||||||
function incremental(streamProvider, initial, supportsCancellation) {
|
var input = es.through();
|
||||||
var input = es.through();
|
var output = es.through();
|
||||||
var output = es.through();
|
var state = 'idle';
|
||||||
var state = 'idle';
|
var buffer = Object.create(null);
|
||||||
var buffer = Object.create(null);
|
var token = !supportsCancellation ? null : { isCancellationRequested: function () { return Object.keys(buffer).length > 0; } };
|
||||||
var token = !supportsCancellation ? null : { isCancellationRequested: function () { return Object.keys(buffer).length > 0; } };
|
var run = function (input, isCancellable) {
|
||||||
var run = function (input, isCancellable) {
|
state = 'running';
|
||||||
state = 'running';
|
var stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
|
||||||
var stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
|
input
|
||||||
input
|
.pipe(stream)
|
||||||
.pipe(stream)
|
.pipe(es.through(null, function () {
|
||||||
.pipe(es.through(null, function () {
|
state = 'idle';
|
||||||
state = 'idle';
|
eventuallyRun();
|
||||||
eventuallyRun();
|
}))
|
||||||
}))
|
.pipe(output);
|
||||||
.pipe(output);
|
};
|
||||||
};
|
if (initial) {
|
||||||
if (initial) {
|
run(initial, false);
|
||||||
run(initial, false);
|
}
|
||||||
}
|
var eventuallyRun = debounce(function () {
|
||||||
var eventuallyRun = debounce(function () {
|
var paths = Object.keys(buffer);
|
||||||
var paths = Object.keys(buffer);
|
if (paths.length === 0) {
|
||||||
if (paths.length === 0) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
var data = paths.map(function (path) { return buffer[path]; });
|
||||||
var data = paths.map(function (path) { return buffer[path]; });
|
buffer = Object.create(null);
|
||||||
buffer = Object.create(null);
|
run(es.readArray(data), true);
|
||||||
run(es.readArray(data), true);
|
}, 500);
|
||||||
}, 500);
|
input.on('data', function (f) {
|
||||||
input.on('data', function (f) {
|
buffer[f.path] = f;
|
||||||
buffer[f.path] = f;
|
if (state === 'idle') {
|
||||||
if (state === 'idle') {
|
eventuallyRun();
|
||||||
eventuallyRun();
|
}
|
||||||
}
|
});
|
||||||
});
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
}
|
||||||
}
|
exports.incremental = incremental;
|
||||||
exports.incremental = incremental;
|
function fixWin32DirectoryPermissions() {
|
||||||
function fixWin32DirectoryPermissions() {
|
if (!/win32/.test(process.platform)) {
|
||||||
if (!/win32/.test(process.platform)) {
|
return es.through();
|
||||||
return es.through();
|
}
|
||||||
}
|
return es.mapSync(function (f) {
|
||||||
return es.mapSync(function (f) {
|
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
|
||||||
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
|
f.stat.mode = 16877;
|
||||||
f.stat.mode = 16877;
|
}
|
||||||
}
|
return f;
|
||||||
return f;
|
});
|
||||||
});
|
}
|
||||||
}
|
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
|
||||||
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
|
function setExecutableBit(pattern) {
|
||||||
function setExecutableBit(pattern) {
|
var setBit = es.mapSync(function (f) {
|
||||||
var setBit = es.mapSync(function (f) {
|
f.stat.mode = 33261;
|
||||||
f.stat.mode = 33261;
|
return f;
|
||||||
return f;
|
});
|
||||||
});
|
if (!pattern) {
|
||||||
if (!pattern) {
|
return setBit;
|
||||||
return setBit;
|
}
|
||||||
}
|
var input = es.through();
|
||||||
var input = es.through();
|
var filter = _filter(pattern, { restore: true });
|
||||||
var filter = _filter(pattern, { restore: true });
|
var output = input
|
||||||
var output = input
|
.pipe(filter)
|
||||||
.pipe(filter)
|
.pipe(setBit)
|
||||||
.pipe(setBit)
|
.pipe(filter.restore);
|
||||||
.pipe(filter.restore);
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
}
|
||||||
}
|
exports.setExecutableBit = setExecutableBit;
|
||||||
exports.setExecutableBit = setExecutableBit;
|
function toFileUri(filePath) {
|
||||||
function toFileUri(filePath) {
|
var match = filePath.match(/^([a-z])\:(.*)$/i);
|
||||||
var match = filePath.match(/^([a-z])\:(.*)$/i);
|
if (match) {
|
||||||
if (match) {
|
filePath = '/' + match[1].toUpperCase() + ':' + match[2];
|
||||||
filePath = '/' + match[1].toUpperCase() + ':' + match[2];
|
}
|
||||||
}
|
return 'file://' + filePath.replace(/\\/g, '/');
|
||||||
return 'file://' + filePath.replace(/\\/g, '/');
|
}
|
||||||
}
|
exports.toFileUri = toFileUri;
|
||||||
exports.toFileUri = toFileUri;
|
function skipDirectories() {
|
||||||
function skipDirectories() {
|
return es.mapSync(function (f) {
|
||||||
return es.mapSync(function (f) {
|
if (!f.isDirectory()) {
|
||||||
if (!f.isDirectory()) {
|
return f;
|
||||||
return f;
|
}
|
||||||
}
|
});
|
||||||
});
|
}
|
||||||
}
|
exports.skipDirectories = skipDirectories;
|
||||||
exports.skipDirectories = skipDirectories;
|
function cleanNodeModule(name, excludes, includes) {
|
||||||
function cleanNodeModule(name, excludes, includes) {
|
var toGlob = function (path) { return '**/node_modules/' + name + (path ? '/' + path : ''); };
|
||||||
var toGlob = function (path) { return '**/node_modules/' + name + (path ? '/' + path : ''); };
|
var negate = function (str) { return '!' + str; };
|
||||||
var negate = function (str) { return '!' + str; };
|
var allFilter = _filter(toGlob('**'), { restore: true });
|
||||||
var allFilter = _filter(toGlob('**'), { restore: true });
|
var globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob)));
|
||||||
var globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob)));
|
var input = es.through();
|
||||||
var input = es.through();
|
var nodeModuleInput = input.pipe(allFilter);
|
||||||
var nodeModuleInput = input.pipe(allFilter);
|
var output = nodeModuleInput.pipe(_filter(globs));
|
||||||
var output = nodeModuleInput.pipe(_filter(globs));
|
if (includes) {
|
||||||
if (includes) {
|
var includeGlobs = includes.map(toGlob);
|
||||||
var includeGlobs = includes.map(toGlob);
|
output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
|
||||||
output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
|
}
|
||||||
}
|
output = output.pipe(allFilter.restore);
|
||||||
output = output.pipe(allFilter.restore);
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
}
|
||||||
}
|
exports.cleanNodeModule = cleanNodeModule;
|
||||||
exports.cleanNodeModule = cleanNodeModule;
|
function loadSourcemaps() {
|
||||||
function loadSourcemaps() {
|
var input = es.through();
|
||||||
var input = es.through();
|
var output = input
|
||||||
var output = input
|
.pipe(es.map(function (f, cb) {
|
||||||
.pipe(es.map(function (f, cb) {
|
if (f.sourceMap) {
|
||||||
if (f.sourceMap) {
|
cb(null, f);
|
||||||
cb(null, f);
|
return;
|
||||||
return;
|
}
|
||||||
}
|
if (!f.contents) {
|
||||||
if (!f.contents) {
|
cb(new Error('empty file'));
|
||||||
cb(new Error('empty file'));
|
return;
|
||||||
return;
|
}
|
||||||
}
|
var contents = f.contents.toString('utf8');
|
||||||
var contents = f.contents.toString('utf8');
|
var reg = /\/\/# sourceMappingURL=(.*)$/g;
|
||||||
var reg = /\/\/# sourceMappingURL=(.*)$/g;
|
var lastMatch = null, match = null;
|
||||||
var lastMatch = null, match = null;
|
while (match = reg.exec(contents)) {
|
||||||
while (match = reg.exec(contents)) {
|
lastMatch = match;
|
||||||
lastMatch = match;
|
}
|
||||||
}
|
if (!lastMatch) {
|
||||||
if (!lastMatch) {
|
f.sourceMap = {
|
||||||
f.sourceMap = {
|
version: 3,
|
||||||
version: 3,
|
names: [],
|
||||||
names: [],
|
mappings: '',
|
||||||
mappings: '',
|
sources: [f.relative.replace(/\//g, '/')],
|
||||||
sources: [f.relative.replace(/\//g, '/')],
|
sourcesContent: [contents]
|
||||||
sourcesContent: [contents]
|
};
|
||||||
};
|
cb(null, f);
|
||||||
cb(null, f);
|
return;
|
||||||
return;
|
}
|
||||||
}
|
f.contents = new Buffer(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
|
||||||
f.contents = new Buffer(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
|
fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', function (err, contents) {
|
||||||
fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', function (err, contents) {
|
if (err) {
|
||||||
if (err) {
|
return cb(err);
|
||||||
return cb(err);
|
}
|
||||||
}
|
f.sourceMap = JSON.parse(contents);
|
||||||
f.sourceMap = JSON.parse(contents);
|
cb(null, f);
|
||||||
cb(null, f);
|
});
|
||||||
});
|
}));
|
||||||
}));
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
}
|
||||||
}
|
exports.loadSourcemaps = loadSourcemaps;
|
||||||
exports.loadSourcemaps = loadSourcemaps;
|
function stripSourceMappingURL() {
|
||||||
function stripSourceMappingURL() {
|
var input = es.through();
|
||||||
var input = es.through();
|
var output = input
|
||||||
var output = input
|
.pipe(es.mapSync(function (f) {
|
||||||
.pipe(es.mapSync(function (f) {
|
var contents = f.contents.toString('utf8');
|
||||||
var contents = f.contents.toString('utf8');
|
f.contents = new Buffer(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
|
||||||
f.contents = new Buffer(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
|
return f;
|
||||||
return f;
|
}));
|
||||||
}));
|
return es.duplex(input, output);
|
||||||
return es.duplex(input, output);
|
}
|
||||||
}
|
exports.stripSourceMappingURL = stripSourceMappingURL;
|
||||||
exports.stripSourceMappingURL = stripSourceMappingURL;
|
function rimraf(dir) {
|
||||||
function rimraf(dir) {
|
var retries = 0;
|
||||||
var retries = 0;
|
var retry = function (cb) {
|
||||||
var retry = function (cb) {
|
_rimraf(dir, { maxBusyTries: 1 }, function (err) {
|
||||||
_rimraf(dir, { maxBusyTries: 1 }, function (err) {
|
if (!err) {
|
||||||
if (!err) {
|
return cb();
|
||||||
return cb();
|
}
|
||||||
}
|
;
|
||||||
;
|
if (err.code === 'ENOTEMPTY' && ++retries < 5) {
|
||||||
if (err.code === 'ENOTEMPTY' && ++retries < 5) {
|
return setTimeout(function () { return retry(cb); }, 10);
|
||||||
return setTimeout(function () { return retry(cb); }, 10);
|
}
|
||||||
}
|
return cb(err);
|
||||||
return cb(err);
|
});
|
||||||
});
|
};
|
||||||
};
|
return function (cb) { return retry(cb); };
|
||||||
return function (cb) { return retry(cb); };
|
}
|
||||||
}
|
exports.rimraf = rimraf;
|
||||||
exports.rimraf = rimraf;
|
function getVersion(root) {
|
||||||
function getVersion(root) {
|
var version = process.env['BUILD_SOURCEVERSION'];
|
||||||
var version = process.env['BUILD_SOURCEVERSION'];
|
if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
|
||||||
if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
|
version = git.getVersion(root);
|
||||||
version = git.getVersion(root);
|
}
|
||||||
}
|
return version;
|
||||||
return version;
|
}
|
||||||
}
|
exports.getVersion = getVersion;
|
||||||
exports.getVersion = getVersion;
|
function rebase(count) {
|
||||||
function rebase(count) {
|
return rename(function (f) {
|
||||||
return rename(function (f) {
|
var parts = f.dirname.split(/[\/\\]/);
|
||||||
var parts = f.dirname.split(/[\/\\]/);
|
f.dirname = parts.slice(count).join(path.sep);
|
||||||
f.dirname = parts.slice(count).join(path.sep);
|
});
|
||||||
});
|
}
|
||||||
}
|
exports.rebase = rebase;
|
||||||
exports.rebase = rebase;
|
function filter(fn) {
|
||||||
function filter(fn) {
|
var result = es.through(function (data) {
|
||||||
var result = es.through(function (data) {
|
if (fn(data)) {
|
||||||
if (fn(data)) {
|
this.emit('data', data);
|
||||||
this.emit('data', data);
|
}
|
||||||
}
|
else {
|
||||||
else {
|
result.restore.push(data);
|
||||||
result.restore.push(data);
|
}
|
||||||
}
|
});
|
||||||
});
|
result.restore = es.through();
|
||||||
result.restore = es.through();
|
return result;
|
||||||
return result;
|
}
|
||||||
}
|
exports.filter = filter;
|
||||||
exports.filter = filter;
|
|
||||||
|
|||||||
@@ -1,346 +1,343 @@
|
|||||||
/*---------------------------------------------------------------------------------------------
|
/*---------------------------------------------------------------------------------------------
|
||||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||||
*--------------------------------------------------------------------------------------------*/
|
*--------------------------------------------------------------------------------------------*/
|
||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var fs = require("fs");
|
||||||
var fs = require("fs");
|
var ts = require("typescript");
|
||||||
var ts = require("typescript");
|
var path = require("path");
|
||||||
var path = require("path");
|
var util = require('gulp-util');
|
||||||
var util = require('gulp-util');
|
function log(message) {
|
||||||
function log(message) {
|
var rest = [];
|
||||||
var rest = [];
|
for (var _i = 1; _i < arguments.length; _i++) {
|
||||||
for (var _i = 1; _i < arguments.length; _i++) {
|
rest[_i - 1] = arguments[_i];
|
||||||
rest[_i - 1] = arguments[_i];
|
}
|
||||||
}
|
util.log.apply(util, [util.colors.cyan('[monaco.d.ts]'), message].concat(rest));
|
||||||
util.log.apply(util, [util.colors.cyan('[monaco.d.ts]'), message].concat(rest));
|
}
|
||||||
}
|
var SRC = path.join(__dirname, '../../src');
|
||||||
var SRC = path.join(__dirname, '../../src');
|
var OUT_ROOT = path.join(__dirname, '../../');
|
||||||
var OUT_ROOT = path.join(__dirname, '../../');
|
var RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe');
|
||||||
var RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe');
|
var DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts');
|
||||||
var DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts');
|
var CURRENT_PROCESSING_RULE = '';
|
||||||
var CURRENT_PROCESSING_RULE = '';
|
function logErr(message) {
|
||||||
function logErr(message) {
|
var rest = [];
|
||||||
var rest = [];
|
for (var _i = 1; _i < arguments.length; _i++) {
|
||||||
for (var _i = 1; _i < arguments.length; _i++) {
|
rest[_i - 1] = arguments[_i];
|
||||||
rest[_i - 1] = arguments[_i];
|
}
|
||||||
}
|
util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE);
|
||||||
util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE);
|
util.log.apply(util, [util.colors.red('[monaco.d.ts]'), message].concat(rest));
|
||||||
util.log.apply(util, [util.colors.red('[monaco.d.ts]'), message].concat(rest));
|
}
|
||||||
}
|
function moduleIdToPath(out, moduleId) {
|
||||||
function moduleIdToPath(out, moduleId) {
|
if (/\.d\.ts/.test(moduleId)) {
|
||||||
if (/\.d\.ts/.test(moduleId)) {
|
return path.join(SRC, moduleId);
|
||||||
return path.join(SRC, moduleId);
|
}
|
||||||
}
|
return path.join(OUT_ROOT, out, moduleId) + '.d.ts';
|
||||||
return path.join(OUT_ROOT, out, moduleId) + '.d.ts';
|
}
|
||||||
}
|
var SOURCE_FILE_MAP = {};
|
||||||
var SOURCE_FILE_MAP = {};
|
function getSourceFile(out, inputFiles, moduleId) {
|
||||||
function getSourceFile(out, inputFiles, moduleId) {
|
if (!SOURCE_FILE_MAP[moduleId]) {
|
||||||
if (!SOURCE_FILE_MAP[moduleId]) {
|
var filePath = path.normalize(moduleIdToPath(out, moduleId));
|
||||||
var filePath = path.normalize(moduleIdToPath(out, moduleId));
|
if (!inputFiles.hasOwnProperty(filePath)) {
|
||||||
if (!inputFiles.hasOwnProperty(filePath)) {
|
logErr('CANNOT FIND FILE ' + filePath + '. YOU MIGHT NEED TO RESTART gulp');
|
||||||
logErr('CANNOT FIND FILE ' + filePath + '. YOU MIGHT NEED TO RESTART gulp');
|
return null;
|
||||||
return null;
|
}
|
||||||
}
|
var fileContents = inputFiles[filePath];
|
||||||
var fileContents = inputFiles[filePath];
|
var sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5);
|
||||||
var sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5);
|
SOURCE_FILE_MAP[moduleId] = sourceFile;
|
||||||
SOURCE_FILE_MAP[moduleId] = sourceFile;
|
}
|
||||||
}
|
return SOURCE_FILE_MAP[moduleId];
|
||||||
return SOURCE_FILE_MAP[moduleId];
|
}
|
||||||
}
|
function isDeclaration(a) {
|
||||||
function isDeclaration(a) {
|
return (a.kind === ts.SyntaxKind.InterfaceDeclaration
|
||||||
return (a.kind === ts.SyntaxKind.InterfaceDeclaration
|
|| a.kind === ts.SyntaxKind.EnumDeclaration
|
||||||
|| a.kind === ts.SyntaxKind.EnumDeclaration
|
|| a.kind === ts.SyntaxKind.ClassDeclaration
|
||||||
|| a.kind === ts.SyntaxKind.ClassDeclaration
|
|| a.kind === ts.SyntaxKind.TypeAliasDeclaration
|
||||||
|| a.kind === ts.SyntaxKind.TypeAliasDeclaration
|
|| a.kind === ts.SyntaxKind.FunctionDeclaration
|
||||||
|| a.kind === ts.SyntaxKind.FunctionDeclaration
|
|| a.kind === ts.SyntaxKind.ModuleDeclaration);
|
||||||
|| a.kind === ts.SyntaxKind.ModuleDeclaration);
|
}
|
||||||
}
|
function visitTopLevelDeclarations(sourceFile, visitor) {
|
||||||
function visitTopLevelDeclarations(sourceFile, visitor) {
|
var stop = false;
|
||||||
var stop = false;
|
var visit = function (node) {
|
||||||
var visit = function (node) {
|
if (stop) {
|
||||||
if (stop) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
switch (node.kind) {
|
||||||
switch (node.kind) {
|
case ts.SyntaxKind.InterfaceDeclaration:
|
||||||
case ts.SyntaxKind.InterfaceDeclaration:
|
case ts.SyntaxKind.EnumDeclaration:
|
||||||
case ts.SyntaxKind.EnumDeclaration:
|
case ts.SyntaxKind.ClassDeclaration:
|
||||||
case ts.SyntaxKind.ClassDeclaration:
|
case ts.SyntaxKind.VariableStatement:
|
||||||
case ts.SyntaxKind.VariableStatement:
|
case ts.SyntaxKind.TypeAliasDeclaration:
|
||||||
case ts.SyntaxKind.TypeAliasDeclaration:
|
case ts.SyntaxKind.FunctionDeclaration:
|
||||||
case ts.SyntaxKind.FunctionDeclaration:
|
case ts.SyntaxKind.ModuleDeclaration:
|
||||||
case ts.SyntaxKind.ModuleDeclaration:
|
stop = visitor(node);
|
||||||
stop = visitor(node);
|
}
|
||||||
}
|
// if (node.kind !== ts.SyntaxKind.SourceFile) {
|
||||||
// if (node.kind !== ts.SyntaxKind.SourceFile) {
|
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
|
||||||
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
|
// console.log('FOUND TEXT IN NODE: ' + ts.SyntaxKind[node.kind]);
|
||||||
// console.log('FOUND TEXT IN NODE: ' + ts.SyntaxKind[node.kind]);
|
// console.log(getNodeText(sourceFile, node));
|
||||||
// console.log(getNodeText(sourceFile, node));
|
// }
|
||||||
// }
|
// }
|
||||||
// }
|
if (stop) {
|
||||||
if (stop) {
|
return;
|
||||||
return;
|
}
|
||||||
}
|
ts.forEachChild(node, visit);
|
||||||
ts.forEachChild(node, visit);
|
};
|
||||||
};
|
visit(sourceFile);
|
||||||
visit(sourceFile);
|
}
|
||||||
}
|
function getAllTopLevelDeclarations(sourceFile) {
|
||||||
function getAllTopLevelDeclarations(sourceFile) {
|
var all = [];
|
||||||
var all = [];
|
visitTopLevelDeclarations(sourceFile, function (node) {
|
||||||
visitTopLevelDeclarations(sourceFile, function (node) {
|
if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
|
||||||
if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
|
var interfaceDeclaration = node;
|
||||||
var interfaceDeclaration = node;
|
var triviaStart = interfaceDeclaration.pos;
|
||||||
var triviaStart = interfaceDeclaration.pos;
|
var triviaEnd = interfaceDeclaration.name.pos;
|
||||||
var triviaEnd = interfaceDeclaration.name.pos;
|
var triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
|
||||||
var triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
|
// // let nodeText = getNodeText(sourceFile, node);
|
||||||
// // let nodeText = getNodeText(sourceFile, node);
|
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
|
||||||
// if (getNodeText(sourceFile, node).indexOf('SymbolKind') >= 0) {
|
// console.log('TRIVIA: ', triviaText);
|
||||||
// console.log('TRIVIA: ', triviaText);
|
// }
|
||||||
// }
|
if (triviaText.indexOf('@internal') === -1) {
|
||||||
if (triviaText.indexOf('@internal') === -1) {
|
all.push(node);
|
||||||
all.push(node);
|
}
|
||||||
}
|
}
|
||||||
}
|
else {
|
||||||
else {
|
var nodeText = getNodeText(sourceFile, node);
|
||||||
var nodeText = getNodeText(sourceFile, node);
|
if (nodeText.indexOf('@internal') === -1) {
|
||||||
if (nodeText.indexOf('@internal') === -1) {
|
all.push(node);
|
||||||
all.push(node);
|
}
|
||||||
}
|
}
|
||||||
}
|
return false /*continue*/;
|
||||||
return false /*continue*/;
|
});
|
||||||
});
|
return all;
|
||||||
return all;
|
}
|
||||||
}
|
function getTopLevelDeclaration(sourceFile, typeName) {
|
||||||
function getTopLevelDeclaration(sourceFile, typeName) {
|
var result = null;
|
||||||
var result = null;
|
visitTopLevelDeclarations(sourceFile, function (node) {
|
||||||
visitTopLevelDeclarations(sourceFile, function (node) {
|
if (isDeclaration(node)) {
|
||||||
if (isDeclaration(node)) {
|
if (node.name.text === typeName) {
|
||||||
if (node.name.text === typeName) {
|
result = node;
|
||||||
result = node;
|
return true /*stop*/;
|
||||||
return true /*stop*/;
|
}
|
||||||
}
|
return false /*continue*/;
|
||||||
return false /*continue*/;
|
}
|
||||||
}
|
// node is ts.VariableStatement
|
||||||
// node is ts.VariableStatement
|
if (getNodeText(sourceFile, node).indexOf(typeName) >= 0) {
|
||||||
if (getNodeText(sourceFile, node).indexOf(typeName) >= 0) {
|
result = node;
|
||||||
result = node;
|
return true /*stop*/;
|
||||||
return true /*stop*/;
|
}
|
||||||
}
|
return false /*continue*/;
|
||||||
return false /*continue*/;
|
});
|
||||||
});
|
return result;
|
||||||
return result;
|
}
|
||||||
}
|
function getNodeText(sourceFile, node) {
|
||||||
function getNodeText(sourceFile, node) {
|
return sourceFile.getFullText().substring(node.pos, node.end);
|
||||||
return sourceFile.getFullText().substring(node.pos, node.end);
|
}
|
||||||
}
|
function getMassagedTopLevelDeclarationText(sourceFile, declaration) {
|
||||||
function getMassagedTopLevelDeclarationText(sourceFile, declaration) {
|
var result = getNodeText(sourceFile, declaration);
|
||||||
var result = getNodeText(sourceFile, declaration);
|
// if (result.indexOf('MonacoWorker') >= 0) {
|
||||||
// if (result.indexOf('MonacoWorker') >= 0) {
|
// console.log('here!');
|
||||||
// console.log('here!');
|
// // console.log(ts.SyntaxKind[declaration.kind]);
|
||||||
// // console.log(ts.SyntaxKind[declaration.kind]);
|
// }
|
||||||
// }
|
if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
|
||||||
if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
|
var interfaceDeclaration = declaration;
|
||||||
var interfaceDeclaration = declaration;
|
var members = interfaceDeclaration.members;
|
||||||
var members = interfaceDeclaration.members;
|
members.forEach(function (member) {
|
||||||
members.forEach(function (member) {
|
try {
|
||||||
try {
|
var memberText = getNodeText(sourceFile, member);
|
||||||
var memberText = getNodeText(sourceFile, member);
|
if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
|
||||||
if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
|
// console.log('BEFORE: ', result);
|
||||||
// console.log('BEFORE: ', result);
|
result = result.replace(memberText, '');
|
||||||
result = result.replace(memberText, '');
|
}
|
||||||
// console.log('AFTER: ', result);
|
}
|
||||||
}
|
catch (err) {
|
||||||
}
|
}
|
||||||
catch (err) {
|
});
|
||||||
// life..
|
}
|
||||||
}
|
result = result.replace(/export default/g, 'export');
|
||||||
});
|
result = result.replace(/export declare/g, 'export');
|
||||||
}
|
return result;
|
||||||
result = result.replace(/export default/g, 'export');
|
}
|
||||||
result = result.replace(/export declare/g, 'export');
|
function format(text) {
|
||||||
return result;
|
var options = getDefaultOptions();
|
||||||
}
|
// Parse the source text
|
||||||
function format(text) {
|
var sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
|
||||||
var options = getDefaultOptions();
|
// Get the formatting edits on the input sources
|
||||||
// Parse the source text
|
var edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
|
||||||
var sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
|
// Apply the edits on the input code
|
||||||
// Get the formatting edits on the input sources
|
return applyEdits(text, edits);
|
||||||
var edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options);
|
function getRuleProvider(options) {
|
||||||
// Apply the edits on the input code
|
// Share this between multiple formatters using the same options.
|
||||||
return applyEdits(text, edits);
|
// This represents the bulk of the space the formatter uses.
|
||||||
function getRuleProvider(options) {
|
var ruleProvider = new ts.formatting.RulesProvider();
|
||||||
// Share this between multiple formatters using the same options.
|
ruleProvider.ensureUpToDate(options);
|
||||||
// This represents the bulk of the space the formatter uses.
|
return ruleProvider;
|
||||||
var ruleProvider = new ts.formatting.RulesProvider();
|
}
|
||||||
ruleProvider.ensureUpToDate(options);
|
function applyEdits(text, edits) {
|
||||||
return ruleProvider;
|
// Apply edits in reverse on the existing text
|
||||||
}
|
var result = text;
|
||||||
function applyEdits(text, edits) {
|
for (var i = edits.length - 1; i >= 0; i--) {
|
||||||
// Apply edits in reverse on the existing text
|
var change = edits[i];
|
||||||
var result = text;
|
var head = result.slice(0, change.span.start);
|
||||||
for (var i = edits.length - 1; i >= 0; i--) {
|
var tail = result.slice(change.span.start + change.span.length);
|
||||||
var change = edits[i];
|
result = head + change.newText + tail;
|
||||||
var head = result.slice(0, change.span.start);
|
}
|
||||||
var tail = result.slice(change.span.start + change.span.length);
|
return result;
|
||||||
result = head + change.newText + tail;
|
}
|
||||||
}
|
function getDefaultOptions() {
|
||||||
return result;
|
return {
|
||||||
}
|
indentSize: 4,
|
||||||
function getDefaultOptions() {
|
tabSize: 4,
|
||||||
return {
|
newLineCharacter: '\r\n',
|
||||||
indentSize: 4,
|
convertTabsToSpaces: true,
|
||||||
tabSize: 4,
|
indentStyle: ts.IndentStyle.Block,
|
||||||
newLineCharacter: '\r\n',
|
insertSpaceAfterCommaDelimiter: true,
|
||||||
convertTabsToSpaces: true,
|
insertSpaceAfterSemicolonInForStatements: true,
|
||||||
indentStyle: ts.IndentStyle.Block,
|
insertSpaceBeforeAndAfterBinaryOperators: true,
|
||||||
insertSpaceAfterCommaDelimiter: true,
|
insertSpaceAfterKeywordsInControlFlowStatements: true,
|
||||||
insertSpaceAfterSemicolonInForStatements: true,
|
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
|
||||||
insertSpaceBeforeAndAfterBinaryOperators: true,
|
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
|
||||||
insertSpaceAfterKeywordsInControlFlowStatements: true,
|
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
|
||||||
insertSpaceAfterFunctionKeywordForAnonymousFunctions: false,
|
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true,
|
||||||
insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false,
|
placeOpenBraceOnNewLineForFunctions: false,
|
||||||
insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false,
|
placeOpenBraceOnNewLineForControlBlocks: false,
|
||||||
insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true,
|
};
|
||||||
placeOpenBraceOnNewLineForFunctions: false,
|
}
|
||||||
placeOpenBraceOnNewLineForControlBlocks: false,
|
}
|
||||||
};
|
function createReplacer(data) {
|
||||||
}
|
data = data || '';
|
||||||
}
|
var rawDirectives = data.split(';');
|
||||||
function createReplacer(data) {
|
var directives = [];
|
||||||
data = data || '';
|
rawDirectives.forEach(function (rawDirective) {
|
||||||
var rawDirectives = data.split(';');
|
if (rawDirective.length === 0) {
|
||||||
var directives = [];
|
return;
|
||||||
rawDirectives.forEach(function (rawDirective) {
|
}
|
||||||
if (rawDirective.length === 0) {
|
var pieces = rawDirective.split('=>');
|
||||||
return;
|
var findStr = pieces[0];
|
||||||
}
|
var replaceStr = pieces[1];
|
||||||
var pieces = rawDirective.split('=>');
|
findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
|
||||||
var findStr = pieces[0];
|
findStr = '\\b' + findStr + '\\b';
|
||||||
var replaceStr = pieces[1];
|
directives.push([new RegExp(findStr, 'g'), replaceStr]);
|
||||||
findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
|
});
|
||||||
findStr = '\\b' + findStr + '\\b';
|
return function (str) {
|
||||||
directives.push([new RegExp(findStr, 'g'), replaceStr]);
|
for (var i = 0; i < directives.length; i++) {
|
||||||
});
|
str = str.replace(directives[i][0], directives[i][1]);
|
||||||
return function (str) {
|
}
|
||||||
for (var i = 0; i < directives.length; i++) {
|
return str;
|
||||||
str = str.replace(directives[i][0], directives[i][1]);
|
};
|
||||||
}
|
}
|
||||||
return str;
|
function generateDeclarationFile(out, inputFiles, recipe) {
|
||||||
};
|
var lines = recipe.split(/\r\n|\n|\r/);
|
||||||
}
|
var result = [];
|
||||||
function generateDeclarationFile(out, inputFiles, recipe) {
|
lines.forEach(function (line) {
|
||||||
var lines = recipe.split(/\r\n|\n|\r/);
|
var m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||||
var result = [];
|
if (m1) {
|
||||||
lines.forEach(function (line) {
|
CURRENT_PROCESSING_RULE = line;
|
||||||
var m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
var moduleId = m1[1];
|
||||||
if (m1) {
|
var sourceFile_1 = getSourceFile(out, inputFiles, moduleId);
|
||||||
CURRENT_PROCESSING_RULE = line;
|
if (!sourceFile_1) {
|
||||||
var moduleId = m1[1];
|
return;
|
||||||
var sourceFile_1 = getSourceFile(out, inputFiles, moduleId);
|
}
|
||||||
if (!sourceFile_1) {
|
var replacer_1 = createReplacer(m1[2]);
|
||||||
return;
|
var typeNames = m1[3].split(/,/);
|
||||||
}
|
typeNames.forEach(function (typeName) {
|
||||||
var replacer_1 = createReplacer(m1[2]);
|
typeName = typeName.trim();
|
||||||
var typeNames = m1[3].split(/,/);
|
if (typeName.length === 0) {
|
||||||
typeNames.forEach(function (typeName) {
|
return;
|
||||||
typeName = typeName.trim();
|
}
|
||||||
if (typeName.length === 0) {
|
var declaration = getTopLevelDeclaration(sourceFile_1, typeName);
|
||||||
return;
|
if (!declaration) {
|
||||||
}
|
logErr('Cannot find type ' + typeName);
|
||||||
var declaration = getTopLevelDeclaration(sourceFile_1, typeName);
|
return;
|
||||||
if (!declaration) {
|
}
|
||||||
logErr('Cannot find type ' + typeName);
|
result.push(replacer_1(getMassagedTopLevelDeclarationText(sourceFile_1, declaration)));
|
||||||
return;
|
});
|
||||||
}
|
return;
|
||||||
result.push(replacer_1(getMassagedTopLevelDeclarationText(sourceFile_1, declaration)));
|
}
|
||||||
});
|
var m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||||
return;
|
if (m2) {
|
||||||
}
|
CURRENT_PROCESSING_RULE = line;
|
||||||
var m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
var moduleId = m2[1];
|
||||||
if (m2) {
|
var sourceFile_2 = getSourceFile(out, inputFiles, moduleId);
|
||||||
CURRENT_PROCESSING_RULE = line;
|
if (!sourceFile_2) {
|
||||||
var moduleId = m2[1];
|
return;
|
||||||
var sourceFile_2 = getSourceFile(out, inputFiles, moduleId);
|
}
|
||||||
if (!sourceFile_2) {
|
var replacer_2 = createReplacer(m2[2]);
|
||||||
return;
|
var typeNames = m2[3].split(/,/);
|
||||||
}
|
var typesToExcludeMap_1 = {};
|
||||||
var replacer_2 = createReplacer(m2[2]);
|
var typesToExcludeArr_1 = [];
|
||||||
var typeNames = m2[3].split(/,/);
|
typeNames.forEach(function (typeName) {
|
||||||
var typesToExcludeMap_1 = {};
|
typeName = typeName.trim();
|
||||||
var typesToExcludeArr_1 = [];
|
if (typeName.length === 0) {
|
||||||
typeNames.forEach(function (typeName) {
|
return;
|
||||||
typeName = typeName.trim();
|
}
|
||||||
if (typeName.length === 0) {
|
typesToExcludeMap_1[typeName] = true;
|
||||||
return;
|
typesToExcludeArr_1.push(typeName);
|
||||||
}
|
});
|
||||||
typesToExcludeMap_1[typeName] = true;
|
getAllTopLevelDeclarations(sourceFile_2).forEach(function (declaration) {
|
||||||
typesToExcludeArr_1.push(typeName);
|
if (isDeclaration(declaration)) {
|
||||||
});
|
if (typesToExcludeMap_1[declaration.name.text]) {
|
||||||
getAllTopLevelDeclarations(sourceFile_2).forEach(function (declaration) {
|
return;
|
||||||
if (isDeclaration(declaration)) {
|
}
|
||||||
if (typesToExcludeMap_1[declaration.name.text]) {
|
}
|
||||||
return;
|
else {
|
||||||
}
|
// node is ts.VariableStatement
|
||||||
}
|
var nodeText = getNodeText(sourceFile_2, declaration);
|
||||||
else {
|
for (var i = 0; i < typesToExcludeArr_1.length; i++) {
|
||||||
// node is ts.VariableStatement
|
if (nodeText.indexOf(typesToExcludeArr_1[i]) >= 0) {
|
||||||
var nodeText = getNodeText(sourceFile_2, declaration);
|
return;
|
||||||
for (var i = 0; i < typesToExcludeArr_1.length; i++) {
|
}
|
||||||
if (nodeText.indexOf(typesToExcludeArr_1[i]) >= 0) {
|
}
|
||||||
return;
|
}
|
||||||
}
|
result.push(replacer_2(getMassagedTopLevelDeclarationText(sourceFile_2, declaration)));
|
||||||
}
|
});
|
||||||
}
|
return;
|
||||||
result.push(replacer_2(getMassagedTopLevelDeclarationText(sourceFile_2, declaration)));
|
}
|
||||||
});
|
result.push(line);
|
||||||
return;
|
});
|
||||||
}
|
var resultTxt = result.join('\n');
|
||||||
result.push(line);
|
resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
|
||||||
});
|
resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
|
||||||
var resultTxt = result.join('\n');
|
resultTxt = resultTxt.replace(/\bTPromise</g, 'Promise<');
|
||||||
resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
|
resultTxt = format(resultTxt);
|
||||||
resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
|
resultTxt = resultTxt.replace(/\r\n/g, '\n');
|
||||||
resultTxt = resultTxt.replace(/\bTPromise</g, 'Promise<');
|
return resultTxt;
|
||||||
resultTxt = format(resultTxt);
|
}
|
||||||
resultTxt = resultTxt.replace(/\r\n/g, '\n');
|
function getFilesToWatch(out) {
|
||||||
return resultTxt;
|
var recipe = fs.readFileSync(RECIPE_PATH).toString();
|
||||||
}
|
var lines = recipe.split(/\r\n|\n|\r/);
|
||||||
function getFilesToWatch(out) {
|
var result = [];
|
||||||
var recipe = fs.readFileSync(RECIPE_PATH).toString();
|
lines.forEach(function (line) {
|
||||||
var lines = recipe.split(/\r\n|\n|\r/);
|
var m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||||
var result = [];
|
if (m1) {
|
||||||
lines.forEach(function (line) {
|
var moduleId = m1[1];
|
||||||
var m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
result.push(moduleIdToPath(out, moduleId));
|
||||||
if (m1) {
|
return;
|
||||||
var moduleId = m1[1];
|
}
|
||||||
result.push(moduleIdToPath(out, moduleId));
|
var m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||||
return;
|
if (m2) {
|
||||||
}
|
var moduleId = m2[1];
|
||||||
var m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
result.push(moduleIdToPath(out, moduleId));
|
||||||
if (m2) {
|
return;
|
||||||
var moduleId = m2[1];
|
}
|
||||||
result.push(moduleIdToPath(out, moduleId));
|
});
|
||||||
return;
|
return result;
|
||||||
}
|
}
|
||||||
});
|
exports.getFilesToWatch = getFilesToWatch;
|
||||||
return result;
|
function run(out, inputFiles) {
|
||||||
}
|
log('Starting monaco.d.ts generation');
|
||||||
exports.getFilesToWatch = getFilesToWatch;
|
SOURCE_FILE_MAP = {};
|
||||||
function run(out, inputFiles) {
|
var recipe = fs.readFileSync(RECIPE_PATH).toString();
|
||||||
log('Starting monaco.d.ts generation');
|
var result = generateDeclarationFile(out, inputFiles, recipe);
|
||||||
SOURCE_FILE_MAP = {};
|
var currentContent = fs.readFileSync(DECLARATION_PATH).toString();
|
||||||
var recipe = fs.readFileSync(RECIPE_PATH).toString();
|
log('Finished monaco.d.ts generation');
|
||||||
var result = generateDeclarationFile(out, inputFiles, recipe);
|
return {
|
||||||
var currentContent = fs.readFileSync(DECLARATION_PATH).toString();
|
content: result,
|
||||||
log('Finished monaco.d.ts generation');
|
filePath: DECLARATION_PATH,
|
||||||
return {
|
isTheSame: currentContent === result
|
||||||
content: result,
|
};
|
||||||
filePath: DECLARATION_PATH,
|
}
|
||||||
isTheSame: currentContent === result
|
exports.run = run;
|
||||||
};
|
function complainErrors() {
|
||||||
}
|
logErr('Not running monaco.d.ts generation due to compile errors');
|
||||||
exports.run = run;
|
}
|
||||||
function complainErrors() {
|
exports.complainErrors = complainErrors;
|
||||||
logErr('Not running monaco.d.ts generation due to compile errors');
|
|
||||||
}
|
|
||||||
exports.complainErrors = complainErrors;
|
|
||||||
|
|||||||
Reference in New Issue
Block a user