mirror of
https://github.com/Microsoft/vscode
synced 2024-10-02 17:32:41 +00:00
auto-fixed prefer-const violation
This commit is contained in:
parent
aa23a0dbb7
commit
0656d21d11
|
@ -19,7 +19,7 @@ shasum.update(fs.readFileSync(path.join(ROOT, '.yarnrc')));
|
|||
shasum.update(fs.readFileSync(path.join(ROOT, 'remote/.yarnrc')));
|
||||
|
||||
// Add `package.json` and `yarn.lock` files
|
||||
for (let dir of dirs) {
|
||||
for (const dir of dirs) {
|
||||
const packageJsonPath = path.join(ROOT, dir, 'package.json');
|
||||
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
|
||||
const relevantPackageJsonSections = {
|
||||
|
|
|
@ -45,7 +45,7 @@ async function main() {
|
|||
force: true
|
||||
});
|
||||
|
||||
let productJson = await fs.readJson(productJsonPath);
|
||||
const productJson = await fs.readJson(productJsonPath);
|
||||
Object.assign(productJson, {
|
||||
darwinUniversalAssetId: 'darwin-universal'
|
||||
});
|
||||
|
|
|
@ -17,14 +17,14 @@ const compilation = require('./lib/compilation');
|
|||
const monacoapi = require('./lib/monaco-api');
|
||||
const fs = require('fs');
|
||||
|
||||
let root = path.dirname(__dirname);
|
||||
let sha1 = util.getVersion(root);
|
||||
let semver = require('./monaco/package.json').version;
|
||||
let headerVersion = semver + '(' + sha1 + ')';
|
||||
const root = path.dirname(__dirname);
|
||||
const sha1 = util.getVersion(root);
|
||||
const semver = require('./monaco/package.json').version;
|
||||
const headerVersion = semver + '(' + sha1 + ')';
|
||||
|
||||
// Build
|
||||
|
||||
let editorEntryPoints = [
|
||||
const editorEntryPoints = [
|
||||
{
|
||||
name: 'vs/editor/editor.main',
|
||||
include: [],
|
||||
|
@ -40,11 +40,11 @@ let editorEntryPoints = [
|
|||
}
|
||||
];
|
||||
|
||||
let editorResources = [
|
||||
const editorResources = [
|
||||
'out-editor-build/vs/base/browser/ui/codicons/**/*.ttf'
|
||||
];
|
||||
|
||||
let BUNDLED_FILE_HEADER = [
|
||||
const BUNDLED_FILE_HEADER = [
|
||||
'/*!-----------------------------------------------------------',
|
||||
' * Copyright (c) Microsoft Corporation. All rights reserved.',
|
||||
' * Version: ' + headerVersion,
|
||||
|
@ -224,7 +224,7 @@ const appendJSToESMImportsTask = task.define('append-js-to-esm-imports', () => {
|
|||
result.push(line);
|
||||
continue;
|
||||
}
|
||||
let modifiedLine = (
|
||||
const modifiedLine = (
|
||||
line
|
||||
.replace(/^import(.*)\'([^']+)\'/, `import$1'$2.js'`)
|
||||
.replace(/^export \* from \'([^']+)\'/, `export * from '$1.js'`)
|
||||
|
@ -239,10 +239,10 @@ const appendJSToESMImportsTask = task.define('append-js-to-esm-imports', () => {
|
|||
* @param {string} contents
|
||||
*/
|
||||
function toExternalDTS(contents) {
|
||||
let lines = contents.split(/\r\n|\r|\n/);
|
||||
const lines = contents.split(/\r\n|\r|\n/);
|
||||
let killNextCloseCurlyBrace = false;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
let line = lines[i];
|
||||
const line = lines[i];
|
||||
|
||||
if (killNextCloseCurlyBrace) {
|
||||
if ('}' === line) {
|
||||
|
@ -316,7 +316,7 @@ const finalEditorResourcesTask = task.define('final-editor-resources', () => {
|
|||
// package.json
|
||||
gulp.src('build/monaco/package.json')
|
||||
.pipe(es.through(function (data) {
|
||||
let json = JSON.parse(data.contents.toString());
|
||||
const json = JSON.parse(data.contents.toString());
|
||||
json.private = false;
|
||||
data.contents = Buffer.from(JSON.stringify(json, null, ' '));
|
||||
this.emit('data', data);
|
||||
|
@ -360,10 +360,10 @@ const finalEditorResourcesTask = task.define('final-editor-resources', () => {
|
|||
return;
|
||||
}
|
||||
|
||||
let relativePathToMap = path.relative(path.join(data.relative), path.join('min-maps', data.relative + '.map'));
|
||||
const relativePathToMap = path.relative(path.join(data.relative), path.join('min-maps', data.relative + '.map'));
|
||||
|
||||
let strContents = data.contents.toString();
|
||||
let newStr = '//# sourceMappingURL=' + relativePathToMap.replace(/\\/g, '/');
|
||||
const newStr = '//# sourceMappingURL=' + relativePathToMap.replace(/\\/g, '/');
|
||||
strContents = strContents.replace(/\/\/# sourceMappingURL=[^ ]+$/, newStr);
|
||||
|
||||
data.contents = Buffer.from(strContents);
|
||||
|
@ -483,13 +483,13 @@ function createTscCompileTask(watch) {
|
|||
cwd: path.join(__dirname, '..'),
|
||||
// stdio: [null, 'pipe', 'inherit']
|
||||
});
|
||||
let errors = [];
|
||||
let reporter = createReporter('monaco');
|
||||
const errors = [];
|
||||
const reporter = createReporter('monaco');
|
||||
|
||||
/** @type {NodeJS.ReadWriteStream | undefined} */
|
||||
let report;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
let magic = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; // https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings
|
||||
const magic = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; // https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings
|
||||
|
||||
child.stdout.on('data', data => {
|
||||
let str = String(data);
|
||||
|
@ -502,12 +502,12 @@ function createTscCompileTask(watch) {
|
|||
report.end();
|
||||
|
||||
} else if (str) {
|
||||
let match = /(.*\(\d+,\d+\): )(.*: )(.*)/.exec(str);
|
||||
const match = /(.*\(\d+,\d+\): )(.*: )(.*)/.exec(str);
|
||||
if (match) {
|
||||
// trying to massage the message so that it matches the gulp-tsb error messages
|
||||
// e.g. src/vs/base/common/strings.ts(663,5): error TS2322: Type '1234' is not assignable to type 'string'.
|
||||
let fullpath = path.join(root, match[1]);
|
||||
let message = match[3];
|
||||
const fullpath = path.join(root, match[1]);
|
||||
const message = match[3];
|
||||
reporter(fullpath + message);
|
||||
} else {
|
||||
reporter(str);
|
||||
|
|
|
@ -91,7 +91,7 @@ const tasks = compilations.map(function (tsconfigFile) {
|
|||
const baseUrl = getBaseUrl(out);
|
||||
|
||||
let headerId, headerOut;
|
||||
let index = relativeDirname.indexOf('/');
|
||||
const index = relativeDirname.indexOf('/');
|
||||
if (index < 0) {
|
||||
headerId = 'vscode.' + relativeDirname;
|
||||
headerOut = 'out';
|
||||
|
|
|
@ -16,7 +16,7 @@ function checkPackageJSON(actualPath) {
|
|||
const actual = require(path.join(__dirname, '..', actualPath));
|
||||
const rootPackageJSON = require('../package.json');
|
||||
const checkIncluded = (set1, set2) => {
|
||||
for (let depName in set1) {
|
||||
for (const depName in set1) {
|
||||
const depVersion = set1[depName];
|
||||
const rootDepVersion = set2[depName];
|
||||
if (!rootDepVersion) {
|
||||
|
|
|
@ -281,7 +281,7 @@ function packageTask(type, platform, arch, sourceFolderName, destinationFolderNa
|
|||
].map(resource => gulp.src(resource, { base: '.' }).pipe(rename(resource)));
|
||||
}
|
||||
|
||||
let all = es.merge(
|
||||
const all = es.merge(
|
||||
packageJsonStream,
|
||||
productJsonStream,
|
||||
license,
|
||||
|
|
|
@ -122,9 +122,9 @@ gulp.task(core);
|
|||
* @return {Object} A map of paths to checksums.
|
||||
*/
|
||||
function computeChecksums(out, filenames) {
|
||||
let result = {};
|
||||
const result = {};
|
||||
filenames.forEach(function (filename) {
|
||||
let fullPath = path.join(process.cwd(), out, filename);
|
||||
const fullPath = path.join(process.cwd(), out, filename);
|
||||
result[filename] = computeChecksum(fullPath);
|
||||
});
|
||||
return result;
|
||||
|
@ -137,9 +137,9 @@ function computeChecksums(out, filenames) {
|
|||
* @return {string} The checksum for `filename`.
|
||||
*/
|
||||
function computeChecksum(filename) {
|
||||
let contents = fs.readFileSync(filename);
|
||||
const contents = fs.readFileSync(filename);
|
||||
|
||||
let hash = crypto
|
||||
const hash = crypto
|
||||
.createHash('md5')
|
||||
.update(contents)
|
||||
.digest('base64')
|
||||
|
@ -453,20 +453,20 @@ gulp.task(task.define(
|
|||
|
||||
gulp.task('vscode-translations-pull', function () {
|
||||
return es.merge([...i18n.defaultLanguages, ...i18n.extraLanguages].map(language => {
|
||||
let includeDefault = !!innoSetupConfig[language.id].defaultInfo;
|
||||
const includeDefault = !!innoSetupConfig[language.id].defaultInfo;
|
||||
return i18n.pullSetupXlfFiles(apiHostname, apiName, apiToken, language, includeDefault).pipe(vfs.dest(`../vscode-translations-import/${language.id}/setup`));
|
||||
}));
|
||||
});
|
||||
|
||||
gulp.task('vscode-translations-import', function () {
|
||||
let options = minimist(process.argv.slice(2), {
|
||||
const options = minimist(process.argv.slice(2), {
|
||||
string: 'location',
|
||||
default: {
|
||||
location: '../vscode-translations-import'
|
||||
}
|
||||
});
|
||||
return es.merge([...i18n.defaultLanguages, ...i18n.extraLanguages].map(language => {
|
||||
let id = language.id;
|
||||
const id = language.id;
|
||||
return gulp.src(`${options.location}/${id}/vscode-setup/messages.xlf`)
|
||||
.pipe(i18n.prepareIslFiles(language, innoSetupConfig[language.id]))
|
||||
.pipe(vfs.dest(`./build/win32/i18n`));
|
||||
|
|
|
@ -208,7 +208,7 @@ function packageTask(sourceFolderName, destinationFolderName) {
|
|||
gulp.src('resources/server/code-512.png', { base: 'resources/server' })
|
||||
);
|
||||
|
||||
let all = es.merge(
|
||||
const all = es.merge(
|
||||
packageJsonStream,
|
||||
license,
|
||||
sources,
|
||||
|
@ -218,7 +218,7 @@ function packageTask(sourceFolderName, destinationFolderName) {
|
|||
pwaicons
|
||||
);
|
||||
|
||||
let result = all
|
||||
const result = all
|
||||
.pipe(util.skipDirectories())
|
||||
.pipe(util.fixWin32DirectoryPermissions());
|
||||
|
||||
|
|
|
@ -116,8 +116,8 @@ function hygiene(some, linting = true) {
|
|||
})
|
||||
.then(
|
||||
(result) => {
|
||||
let original = result.src.replace(/\r\n/gm, '\n');
|
||||
let formatted = result.dest.replace(/\r\n/gm, '\n');
|
||||
const original = result.src.replace(/\r\n/gm, '\n');
|
||||
const formatted = result.dest.replace(/\r\n/gm, '\n');
|
||||
|
||||
if (original !== formatted) {
|
||||
console.error(
|
||||
|
|
|
@ -98,7 +98,7 @@ export function createAsar(folderPath: string, unpackGlobs: string[], destFilena
|
|||
}
|
||||
}, function () {
|
||||
|
||||
let finish = () => {
|
||||
const finish = () => {
|
||||
{
|
||||
const headerPickle = pickle.createEmpty();
|
||||
headerPickle.writeString(JSON.stringify(filesystem.header));
|
||||
|
|
|
@ -143,7 +143,7 @@ export function getBuiltInExtensions(): Promise<void> {
|
|||
const streams: Stream[] = [];
|
||||
|
||||
for (const extension of [...builtInExtensions, ...webBuiltInExtensions]) {
|
||||
let controlState = control[extension.name] || 'marketplace';
|
||||
const controlState = control[extension.name] || 'marketplace';
|
||||
control[extension.name] = controlState;
|
||||
|
||||
streams.push(syncExtension(extension, controlState));
|
||||
|
|
|
@ -26,7 +26,7 @@ const reporter = createReporter();
|
|||
|
||||
function getTypeScriptCompilerOptions(src: string): ts.CompilerOptions {
|
||||
const rootDir = path.join(__dirname, `../../${src}`);
|
||||
let options: ts.CompilerOptions = {};
|
||||
const options: ts.CompilerOptions = {};
|
||||
options.verbose = false;
|
||||
options.sourceMap = true;
|
||||
if (process.env['VSCODE_NO_SOURCEMAP']) { // To be used by developers in a hurry
|
||||
|
@ -96,7 +96,7 @@ export function compileTask(src: string, out: string, build: boolean): () => Nod
|
|||
|
||||
const compile = createCompile(src, build, true);
|
||||
const srcPipe = gulp.src(`${src}/**`, { base: `${src}` });
|
||||
let generator = new MonacoGenerator(false);
|
||||
const generator = new MonacoGenerator(false);
|
||||
if (src === 'src') {
|
||||
generator.execute();
|
||||
}
|
||||
|
@ -116,7 +116,7 @@ export function watchTask(out: string, build: boolean): () => NodeJS.ReadWriteSt
|
|||
const src = gulp.src('src/**', { base: 'src' });
|
||||
const watchSrc = watch('src/**', { base: 'src', readDelay: 200 });
|
||||
|
||||
let generator = new MonacoGenerator(true);
|
||||
const generator = new MonacoGenerator(true);
|
||||
generator.execute();
|
||||
|
||||
return watchSrc
|
||||
|
@ -140,7 +140,7 @@ class MonacoGenerator {
|
|||
this._isWatch = isWatch;
|
||||
this.stream = es.through();
|
||||
this._watchedFiles = {};
|
||||
let onWillReadFile = (moduleId: string, filePath: string) => {
|
||||
const onWillReadFile = (moduleId: string, filePath: string) => {
|
||||
if (!this._isWatch) {
|
||||
return;
|
||||
}
|
||||
|
@ -182,7 +182,7 @@ class MonacoGenerator {
|
|||
}
|
||||
|
||||
private _run(): monacodts.IMonacoDeclarationResult | null {
|
||||
let r = monacodts.run3(this._declarationResolver);
|
||||
const r = monacodts.run3(this._declarationResolver);
|
||||
if (!r && !this._isWatch) {
|
||||
// The build must always be able to generate the monaco.d.ts
|
||||
throw new Error(`monaco.d.ts generation error - Cannot continue`);
|
||||
|
|
|
@ -51,7 +51,7 @@ export = new class NoUnexternalizedStrings implements eslint.Rule.RuleModule {
|
|||
key = keyNode.value;
|
||||
|
||||
} else if (keyNode.type === AST_NODE_TYPES.ObjectExpression) {
|
||||
for (let property of keyNode.properties) {
|
||||
for (const property of keyNode.properties) {
|
||||
if (property.type === AST_NODE_TYPES.Property && !property.computed) {
|
||||
if (property.key.type === AST_NODE_TYPES.Identifier && property.key.name === 'key') {
|
||||
if (isStringLiteral(property.value)) {
|
||||
|
@ -97,7 +97,7 @@ export = new class NoUnexternalizedStrings implements eslint.Rule.RuleModule {
|
|||
// (2)
|
||||
// report all invalid NLS keys
|
||||
if (!key.match(NoUnexternalizedStrings._rNlsKeys)) {
|
||||
for (let value of values) {
|
||||
for (const value of values) {
|
||||
context.report({ loc: value.call.loc, messageId: 'badKey', data: { key } });
|
||||
}
|
||||
}
|
||||
|
|
|
@ -20,7 +20,7 @@ export = new class ApiProviderNaming implements eslint.Rule.RuleModule {
|
|||
['TSInterfaceDeclaration[id.name=/.+Provider/] TSMethodSignature[key.name=/^(provide|resolve).+/]']: (node: any) => {
|
||||
|
||||
let found = false;
|
||||
for (let param of (<TSESTree.TSMethodSignature>node).params) {
|
||||
for (const param of (<TSESTree.TSMethodSignature>node).params) {
|
||||
if (param.type === AST_NODE_TYPES.Identifier) {
|
||||
found = found || param.name === 'token';
|
||||
}
|
||||
|
|
|
@ -430,7 +430,7 @@ export function scanBuiltinExtensions(extensionsRoot: string, exclude: string[]
|
|||
if (!fs.existsSync(packageJSONPath)) {
|
||||
continue;
|
||||
}
|
||||
let packageJSON = JSON.parse(fs.readFileSync(packageJSONPath).toString('utf8'));
|
||||
const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath).toString('utf8'));
|
||||
if (!isWebExtension(packageJSON)) {
|
||||
continue;
|
||||
}
|
||||
|
@ -461,7 +461,7 @@ export function translatePackageJSON(packageJSON: string, packageNLSPath: string
|
|||
const CharCode_PC = '%'.charCodeAt(0);
|
||||
const packageNls: NLSFormat = JSON.parse(fs.readFileSync(packageNLSPath).toString());
|
||||
const translate = (obj: any) => {
|
||||
for (let key in obj) {
|
||||
for (const key in obj) {
|
||||
const val = obj[key];
|
||||
if (Array.isArray(val)) {
|
||||
val.forEach(translate);
|
||||
|
|
|
@ -51,7 +51,7 @@ export function getVersion(repo: string): string | undefined {
|
|||
|
||||
const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
|
||||
let refsMatch: RegExpExecArray | null;
|
||||
let refs: { [ref: string]: string } = {};
|
||||
const refs: { [ref: string]: string } = {};
|
||||
|
||||
while (refsMatch = refsRegex.exec(refsRaw)) {
|
||||
refs[refsMatch[2]] = refsMatch[1];
|
||||
|
|
|
@ -87,7 +87,7 @@ interface LocalizeInfo {
|
|||
|
||||
module LocalizeInfo {
|
||||
export function is(value: any): value is LocalizeInfo {
|
||||
let candidate = value as LocalizeInfo;
|
||||
const candidate = value as LocalizeInfo;
|
||||
return Is.defined(candidate) && Is.string(candidate.key) && (Is.undef(candidate.comment) || (Is.array(candidate.comment) && candidate.comment.every(element => Is.string(element))));
|
||||
}
|
||||
}
|
||||
|
@ -104,8 +104,8 @@ module BundledFormat {
|
|||
return false;
|
||||
}
|
||||
|
||||
let candidate = value as BundledFormat;
|
||||
let length = Object.keys(value).length;
|
||||
const candidate = value as BundledFormat;
|
||||
const length = Object.keys(value).length;
|
||||
|
||||
return length === 3 && Is.defined(candidate.keys) && Is.defined(candidate.messages) && Is.defined(candidate.bundles);
|
||||
}
|
||||
|
@ -126,7 +126,7 @@ module PackageJsonFormat {
|
|||
return false;
|
||||
}
|
||||
return Object.keys(value).every(key => {
|
||||
let element = value[key];
|
||||
const element = value[key];
|
||||
return Is.string(element) || (Is.object(element) && Is.defined(element.message) && Is.defined(element.comment));
|
||||
});
|
||||
}
|
||||
|
@ -218,9 +218,9 @@ export class XLF {
|
|||
}
|
||||
this.numberOfMessages += keys.length;
|
||||
this.files[original] = [];
|
||||
let existingKeys = new Set<string>();
|
||||
const existingKeys = new Set<string>();
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
let key = keys[i];
|
||||
const key = keys[i];
|
||||
let realKey: string | undefined;
|
||||
let comment: string | undefined;
|
||||
if (Is.string(key)) {
|
||||
|
@ -236,7 +236,7 @@ export class XLF {
|
|||
continue;
|
||||
}
|
||||
existingKeys.add(realKey);
|
||||
let message: string = encodeEntities(messages[i]);
|
||||
const message: string = encodeEntities(messages[i]);
|
||||
this.files[original].push({ id: realKey, message: message, comment: comment });
|
||||
}
|
||||
}
|
||||
|
@ -269,15 +269,15 @@ export class XLF {
|
|||
}
|
||||
|
||||
private appendNewLine(content: string, indent?: number): void {
|
||||
let line = new Line(indent);
|
||||
const line = new Line(indent);
|
||||
line.append(content);
|
||||
this.buffer.push(line.toString());
|
||||
}
|
||||
|
||||
static parsePseudo = function (xlfString: string): Promise<ParsedXLF[]> {
|
||||
return new Promise((resolve) => {
|
||||
let parser = new xml2js.Parser();
|
||||
let files: { messages: Map<string>; originalFilePath: string; language: string }[] = [];
|
||||
const parser = new xml2js.Parser();
|
||||
const files: { messages: Map<string>; originalFilePath: string; language: string }[] = [];
|
||||
parser.parseString(xlfString, function (_err: any, result: any) {
|
||||
const fileNodes: any[] = result['xliff']['file'];
|
||||
fileNodes.forEach(file => {
|
||||
|
@ -302,9 +302,9 @@ export class XLF {
|
|||
|
||||
static parse = function (xlfString: string): Promise<ParsedXLF[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let parser = new xml2js.Parser();
|
||||
const parser = new xml2js.Parser();
|
||||
|
||||
let files: { messages: Map<string>; originalFilePath: string; language: string }[] = [];
|
||||
const files: { messages: Map<string>; originalFilePath: string; language: string }[] = [];
|
||||
|
||||
parser.parseString(xlfString, function (err: any, result: any) {
|
||||
if (err) {
|
||||
|
@ -321,7 +321,7 @@ export class XLF {
|
|||
if (!originalFilePath) {
|
||||
reject(new Error(`XLF parsing error: XLIFF file node does not contain original attribute to determine the original location of the resource file.`));
|
||||
}
|
||||
let language = file.$['target-language'];
|
||||
const language = file.$['target-language'];
|
||||
if (!language) {
|
||||
reject(new Error(`XLF parsing error: XLIFF file node does not contain target-language attribute to determine translated language.`));
|
||||
}
|
||||
|
@ -413,7 +413,7 @@ function stripComments(content: string): string {
|
|||
// Third group matches a multi line comment
|
||||
// Forth group matches a single line comment
|
||||
const regexp = /("[^"\\]*(?:\\.[^"\\]*)*")|('[^'\\]*(?:\\.[^'\\]*)*')|(\/\*[^\/\*]*(?:(?:\*|\/)[^\/\*]*)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
|
||||
let result = content.replace(regexp, (match, _m1: string, _m2: string, m3: string, m4: string) => {
|
||||
const result = content.replace(regexp, (match, _m1: string, _m2: string, m3: string, m4: string) => {
|
||||
// Only one of m1, m2, m3, m4 matches
|
||||
if (m3) {
|
||||
// A block comment. Replace with nothing
|
||||
|
@ -472,22 +472,22 @@ function escapeCharacters(value: string): string {
|
|||
}
|
||||
|
||||
function processCoreBundleFormat(fileHeader: string, languages: Language[], json: BundledFormat, emitter: ThroughStream) {
|
||||
let keysSection = json.keys;
|
||||
let messageSection = json.messages;
|
||||
let bundleSection = json.bundles;
|
||||
const keysSection = json.keys;
|
||||
const messageSection = json.messages;
|
||||
const bundleSection = json.bundles;
|
||||
|
||||
let statistics: Map<number> = Object.create(null);
|
||||
const statistics: Map<number> = Object.create(null);
|
||||
|
||||
let defaultMessages: Map<Map<string>> = Object.create(null);
|
||||
let modules = Object.keys(keysSection);
|
||||
const defaultMessages: Map<Map<string>> = Object.create(null);
|
||||
const modules = Object.keys(keysSection);
|
||||
modules.forEach((module) => {
|
||||
let keys = keysSection[module];
|
||||
let messages = messageSection[module];
|
||||
const keys = keysSection[module];
|
||||
const messages = messageSection[module];
|
||||
if (!messages || keys.length !== messages.length) {
|
||||
emitter.emit('error', `Message for module ${module} corrupted. Mismatch in number of keys and messages.`);
|
||||
return;
|
||||
}
|
||||
let messageMap: Map<string> = Object.create(null);
|
||||
const messageMap: Map<string> = Object.create(null);
|
||||
defaultMessages[module] = messageMap;
|
||||
keys.map((key, i) => {
|
||||
if (typeof key === 'string') {
|
||||
|
@ -498,28 +498,28 @@ function processCoreBundleFormat(fileHeader: string, languages: Language[], json
|
|||
});
|
||||
});
|
||||
|
||||
let languageDirectory = path.join(__dirname, '..', '..', '..', 'vscode-loc', 'i18n');
|
||||
const languageDirectory = path.join(__dirname, '..', '..', '..', 'vscode-loc', 'i18n');
|
||||
if (!fs.existsSync(languageDirectory)) {
|
||||
log(`No VS Code localization repository found. Looking at ${languageDirectory}`);
|
||||
log(`To bundle translations please check out the vscode-loc repository as a sibling of the vscode repository.`);
|
||||
}
|
||||
let sortedLanguages = sortLanguages(languages);
|
||||
const sortedLanguages = sortLanguages(languages);
|
||||
sortedLanguages.forEach((language) => {
|
||||
if (process.env['VSCODE_BUILD_VERBOSE']) {
|
||||
log(`Generating nls bundles for: ${language.id}`);
|
||||
}
|
||||
|
||||
statistics[language.id] = 0;
|
||||
let localizedModules: Map<string[]> = Object.create(null);
|
||||
let languageFolderName = language.translationId || language.id;
|
||||
let i18nFile = path.join(languageDirectory, `vscode-language-pack-${languageFolderName}`, 'translations', 'main.i18n.json');
|
||||
const localizedModules: Map<string[]> = Object.create(null);
|
||||
const languageFolderName = language.translationId || language.id;
|
||||
const i18nFile = path.join(languageDirectory, `vscode-language-pack-${languageFolderName}`, 'translations', 'main.i18n.json');
|
||||
let allMessages: I18nFormat | undefined;
|
||||
if (fs.existsSync(i18nFile)) {
|
||||
let content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
|
||||
const content = stripComments(fs.readFileSync(i18nFile, 'utf8'));
|
||||
allMessages = JSON.parse(content);
|
||||
}
|
||||
modules.forEach((module) => {
|
||||
let order = keysSection[module];
|
||||
const order = keysSection[module];
|
||||
let moduleMessage: { [messageKey: string]: string } | undefined;
|
||||
if (allMessages) {
|
||||
moduleMessage = allMessages.contents[module];
|
||||
|
@ -531,7 +531,7 @@ function processCoreBundleFormat(fileHeader: string, languages: Language[], json
|
|||
moduleMessage = defaultMessages[module];
|
||||
statistics[language.id] = statistics[language.id] + Object.keys(moduleMessage).length;
|
||||
}
|
||||
let localizedMessages: string[] = [];
|
||||
const localizedMessages: string[] = [];
|
||||
order.forEach((keyInfo) => {
|
||||
let key: string | null = null;
|
||||
if (typeof keyInfo === 'string') {
|
||||
|
@ -552,14 +552,14 @@ function processCoreBundleFormat(fileHeader: string, languages: Language[], json
|
|||
localizedModules[module] = localizedMessages;
|
||||
});
|
||||
Object.keys(bundleSection).forEach((bundle) => {
|
||||
let modules = bundleSection[bundle];
|
||||
let contents: string[] = [
|
||||
const modules = bundleSection[bundle];
|
||||
const contents: string[] = [
|
||||
fileHeader,
|
||||
`define("${bundle}.nls.${language.id}", {`
|
||||
];
|
||||
modules.forEach((module, index) => {
|
||||
contents.push(`\t"${module}": [`);
|
||||
let messages = localizedModules[module];
|
||||
const messages = localizedModules[module];
|
||||
if (!messages) {
|
||||
emitter.emit('error', `Didn't find messages for module ${module}.`);
|
||||
return;
|
||||
|
@ -574,11 +574,11 @@ function processCoreBundleFormat(fileHeader: string, languages: Language[], json
|
|||
});
|
||||
});
|
||||
Object.keys(statistics).forEach(key => {
|
||||
let value = statistics[key];
|
||||
const value = statistics[key];
|
||||
log(`${key} has ${value} untranslated strings.`);
|
||||
});
|
||||
sortedLanguages.forEach(language => {
|
||||
let stats = statistics[language.id];
|
||||
const stats = statistics[language.id];
|
||||
if (Is.undef(stats)) {
|
||||
log(`\tNo translations found for language ${language.id}. Using default language instead.`);
|
||||
}
|
||||
|
@ -587,7 +587,7 @@ function processCoreBundleFormat(fileHeader: string, languages: Language[], json
|
|||
|
||||
export function processNlsFiles(opts: { fileHeader: string; languages: Language[] }): ThroughStream {
|
||||
return through(function (this: ThroughStream, file: File) {
|
||||
let fileName = path.basename(file.path);
|
||||
const fileName = path.basename(file.path);
|
||||
if (fileName === 'nls.metadata.json') {
|
||||
let json = null;
|
||||
if (file.isBuffer()) {
|
||||
|
@ -643,7 +643,7 @@ export function createXlfFilesForCoreBundle(): ThroughStream {
|
|||
if (file.isBuffer()) {
|
||||
const xlfs: Map<XLF> = Object.create(null);
|
||||
const json: BundledFormat = JSON.parse((file.contents as Buffer).toString('utf8'));
|
||||
for (let coreModule in json.keys) {
|
||||
for (const coreModule in json.keys) {
|
||||
const projectResource = getResource(coreModule);
|
||||
const resource = projectResource.name;
|
||||
const project = projectResource.project;
|
||||
|
@ -662,7 +662,7 @@ export function createXlfFilesForCoreBundle(): ThroughStream {
|
|||
xlf.addFile(`src/${coreModule}`, keys, messages);
|
||||
}
|
||||
}
|
||||
for (let resource in xlfs) {
|
||||
for (const resource in xlfs) {
|
||||
const xlf = xlfs[resource];
|
||||
const filePath = `${xlf.project}/${resource.replace(/\//g, '_')}.xlf`;
|
||||
const xlfFile = new File({
|
||||
|
@ -692,7 +692,7 @@ export function createXlfFilesForExtensions(): ThroughStream {
|
|||
if (!stat.isDirectory()) {
|
||||
return;
|
||||
}
|
||||
let extensionName = path.basename(extensionFolder.path);
|
||||
const extensionName = path.basename(extensionFolder.path);
|
||||
if (extensionName === 'node_modules') {
|
||||
return;
|
||||
}
|
||||
|
@ -725,7 +725,7 @@ export function createXlfFilesForExtensions(): ThroughStream {
|
|||
} else if (basename === 'nls.metadata.json') {
|
||||
const json: BundledExtensionFormat = JSON.parse(buffer.toString('utf8'));
|
||||
const relPath = path.relative(`.build/extensions/${extensionName}`, path.dirname(file.path));
|
||||
for (let file in json) {
|
||||
for (const file in json) {
|
||||
const fileContent = json[file];
|
||||
getXlf().addFile(`extensions/${extensionName}/${relPath}/${file}`, fileContent.keys, fileContent.messages);
|
||||
}
|
||||
|
@ -736,7 +736,7 @@ export function createXlfFilesForExtensions(): ThroughStream {
|
|||
}
|
||||
}, function () {
|
||||
if (_xlf) {
|
||||
let xlfFile = new File({
|
||||
const xlfFile = new File({
|
||||
path: path.join(extensionsProject, extensionName + '.xlf'),
|
||||
contents: Buffer.from(_xlf.toString(), 'utf8')
|
||||
});
|
||||
|
@ -769,17 +769,17 @@ export function createXlfFilesForIsl(): ThroughStream {
|
|||
throw new Error(`Unknown input file ${file.path}`);
|
||||
}
|
||||
|
||||
let xlf = new XLF(projectName),
|
||||
const xlf = new XLF(projectName),
|
||||
keys: string[] = [],
|
||||
messages: string[] = [];
|
||||
|
||||
let model = new TextModel(file.contents.toString());
|
||||
const model = new TextModel(file.contents.toString());
|
||||
let inMessageSection = false;
|
||||
model.lines.forEach(line => {
|
||||
if (line.length === 0) {
|
||||
return;
|
||||
}
|
||||
let firstChar = line.charAt(0);
|
||||
const firstChar = line.charAt(0);
|
||||
switch (firstChar) {
|
||||
case ';':
|
||||
// Comment line;
|
||||
|
@ -791,12 +791,12 @@ export function createXlfFilesForIsl(): ThroughStream {
|
|||
if (!inMessageSection) {
|
||||
return;
|
||||
}
|
||||
let sections: string[] = line.split('=');
|
||||
const sections: string[] = line.split('=');
|
||||
if (sections.length !== 2) {
|
||||
throw new Error(`Badly formatted message found: ${line}`);
|
||||
} else {
|
||||
let key = sections[0];
|
||||
let value = sections[1];
|
||||
const key = sections[0];
|
||||
const value = sections[1];
|
||||
if (key.length > 0 && value.length > 0) {
|
||||
keys.push(key);
|
||||
messages.push(value);
|
||||
|
@ -815,8 +815,8 @@ export function createXlfFilesForIsl(): ThroughStream {
|
|||
}
|
||||
|
||||
export function pushXlfFiles(apiHostname: string, username: string, password: string): ThroughStream {
|
||||
let tryGetPromises: Array<Promise<boolean>> = [];
|
||||
let updateCreatePromises: Array<Promise<boolean>> = [];
|
||||
const tryGetPromises: Array<Promise<boolean>> = [];
|
||||
const updateCreatePromises: Array<Promise<boolean>> = [];
|
||||
|
||||
return through(function (this: ThroughStream, file: File) {
|
||||
const project = path.dirname(file.relative);
|
||||
|
@ -857,11 +857,11 @@ function getAllResources(project: string, apiHostname: string, username: string,
|
|||
};
|
||||
|
||||
const request = https.request(options, (res) => {
|
||||
let buffer: Buffer[] = [];
|
||||
const buffer: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => buffer.push(chunk));
|
||||
res.on('end', () => {
|
||||
if (res.statusCode === 200) {
|
||||
let json = JSON.parse(Buffer.concat(buffer).toString());
|
||||
const json = JSON.parse(Buffer.concat(buffer).toString());
|
||||
if (Array.isArray(json)) {
|
||||
resolve(json.map(o => o.slug));
|
||||
return;
|
||||
|
@ -880,7 +880,7 @@ function getAllResources(project: string, apiHostname: string, username: string,
|
|||
}
|
||||
|
||||
export function findObsoleteResources(apiHostname: string, username: string, password: string): ThroughStream {
|
||||
let resourcesByProject: Map<string[]> = Object.create(null);
|
||||
const resourcesByProject: Map<string[]> = Object.create(null);
|
||||
resourcesByProject[extensionsProject] = ([] as any[]).concat(externalExtensionsWithTranslations); // clone
|
||||
|
||||
return through(function (this: ThroughStream, file: File) {
|
||||
|
@ -897,10 +897,10 @@ export function findObsoleteResources(apiHostname: string, username: string, pas
|
|||
}, function () {
|
||||
|
||||
const json = JSON.parse(fs.readFileSync('./build/lib/i18n.resources.json', 'utf8'));
|
||||
let i18Resources = [...json.editor, ...json.workbench].map((r: Resource) => r.project + '/' + r.name.replace(/\//g, '_'));
|
||||
let extractedResources: string[] = [];
|
||||
for (let project of [workbenchProject, editorProject]) {
|
||||
for (let resource of resourcesByProject[project]) {
|
||||
const i18Resources = [...json.editor, ...json.workbench].map((r: Resource) => r.project + '/' + r.name.replace(/\//g, '_'));
|
||||
const extractedResources: string[] = [];
|
||||
for (const project of [workbenchProject, editorProject]) {
|
||||
for (const resource of resourcesByProject[project]) {
|
||||
if (resource !== 'setup_messages') {
|
||||
extractedResources.push(project + '/' + resource);
|
||||
}
|
||||
|
@ -911,12 +911,12 @@ export function findObsoleteResources(apiHostname: string, username: string, pas
|
|||
console.log(`[i18n] Missing resources in file 'build/lib/i18n.resources.json': JSON.stringify(${extractedResources.filter(p => i18Resources.indexOf(p) === -1)})`);
|
||||
}
|
||||
|
||||
let promises: Array<Promise<void>> = [];
|
||||
for (let project in resourcesByProject) {
|
||||
const promises: Array<Promise<void>> = [];
|
||||
for (const project in resourcesByProject) {
|
||||
promises.push(
|
||||
getAllResources(project, apiHostname, username, password).then(resources => {
|
||||
let expectedResources = resourcesByProject[project];
|
||||
let unusedResources = resources.filter(resource => resource && expectedResources.indexOf(resource) === -1);
|
||||
const expectedResources = resourcesByProject[project];
|
||||
const unusedResources = resources.filter(resource => resource && expectedResources.indexOf(resource) === -1);
|
||||
if (unusedResources.length) {
|
||||
console.log(`[transifex] Obsolete resources in project '${project}': ${unusedResources.join(', ')}`);
|
||||
}
|
||||
|
@ -974,7 +974,7 @@ function createResource(project: string, slug: string, xlfFile: File, apiHostnam
|
|||
method: 'POST'
|
||||
};
|
||||
|
||||
let request = https.request(options, (res) => {
|
||||
const request = https.request(options, (res) => {
|
||||
if (res.statusCode === 201) {
|
||||
log(`Resource ${project}/${slug} successfully created on Transifex.`);
|
||||
} else {
|
||||
|
@ -1008,7 +1008,7 @@ function updateResource(project: string, slug: string, xlfFile: File, apiHostnam
|
|||
method: 'PUT'
|
||||
};
|
||||
|
||||
let request = https.request(options, (res) => {
|
||||
const request = https.request(options, (res) => {
|
||||
if (res.statusCode === 200) {
|
||||
res.setEncoding('utf8');
|
||||
|
||||
|
@ -1035,7 +1035,7 @@ function updateResource(project: string, slug: string, xlfFile: File, apiHostnam
|
|||
}
|
||||
|
||||
export function pullSetupXlfFiles(apiHostname: string, username: string, password: string, language: Language, includeDefault: boolean): NodeJS.ReadableStream {
|
||||
let setupResources = [{ name: 'setup_messages', project: workbenchProject }];
|
||||
const setupResources = [{ name: 'setup_messages', project: workbenchProject }];
|
||||
if (includeDefault) {
|
||||
setupResources.push({ name: 'setup_default', project: setupProject });
|
||||
}
|
||||
|
@ -1044,7 +1044,7 @@ export function pullSetupXlfFiles(apiHostname: string, username: string, passwor
|
|||
|
||||
function pullXlfFiles(apiHostname: string, username: string, password: string, language: Language, resources: Resource[]): NodeJS.ReadableStream {
|
||||
const credentials = `${username}:${password}`;
|
||||
let expectedTranslationsCount = resources.length;
|
||||
const expectedTranslationsCount = resources.length;
|
||||
let translationsRetrieved = 0, called = false;
|
||||
|
||||
return readable(function (_count: any, callback: any) {
|
||||
|
@ -1075,7 +1075,7 @@ function retrieveResource(language: Language, resource: Resource, apiHostname: s
|
|||
return limiter.queue(() => new Promise<File | null>((resolve, reject) => {
|
||||
const slug = resource.name.replace(/\//g, '_');
|
||||
const project = resource.project;
|
||||
let transifexLanguageId = language.id === 'ps' ? 'en' : language.translationId || language.id;
|
||||
const transifexLanguageId = language.id === 'ps' ? 'en' : language.translationId || language.id;
|
||||
const options = {
|
||||
hostname: apiHostname,
|
||||
path: `/api/2/project/${project}/resource/${slug}/translation/${transifexLanguageId}?file&mode=onlyreviewed`,
|
||||
|
@ -1085,8 +1085,8 @@ function retrieveResource(language: Language, resource: Resource, apiHostname: s
|
|||
};
|
||||
console.log('[transifex] Fetching ' + options.path);
|
||||
|
||||
let request = https.request(options, (res) => {
|
||||
let xlfBuffer: Buffer[] = [];
|
||||
const request = https.request(options, (res) => {
|
||||
const xlfBuffer: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => xlfBuffer.push(chunk));
|
||||
res.on('end', () => {
|
||||
if (res.statusCode === 200) {
|
||||
|
@ -1107,16 +1107,16 @@ function retrieveResource(language: Language, resource: Resource, apiHostname: s
|
|||
}
|
||||
|
||||
export function prepareI18nFiles(): ThroughStream {
|
||||
let parsePromises: Promise<ParsedXLF[]>[] = [];
|
||||
const parsePromises: Promise<ParsedXLF[]>[] = [];
|
||||
|
||||
return through(function (this: ThroughStream, xlf: File) {
|
||||
let stream = this;
|
||||
let parsePromise = XLF.parse(xlf.contents.toString());
|
||||
const stream = this;
|
||||
const parsePromise = XLF.parse(xlf.contents.toString());
|
||||
parsePromises.push(parsePromise);
|
||||
parsePromise.then(
|
||||
resolvedFiles => {
|
||||
resolvedFiles.forEach(file => {
|
||||
let translatedFile = createI18nFile(file.originalFilePath, file.messages);
|
||||
const translatedFile = createI18nFile(file.originalFilePath, file.messages);
|
||||
stream.queue(translatedFile);
|
||||
});
|
||||
}
|
||||
|
@ -1129,7 +1129,7 @@ export function prepareI18nFiles(): ThroughStream {
|
|||
}
|
||||
|
||||
function createI18nFile(originalFilePath: string, messages: any): File {
|
||||
let result = Object.create(null);
|
||||
const result = Object.create(null);
|
||||
result[''] = [
|
||||
'--------------------------------------------------------------------------------------------',
|
||||
'Copyright (c) Microsoft Corporation. All rights reserved.',
|
||||
|
@ -1137,7 +1137,7 @@ function createI18nFile(originalFilePath: string, messages: any): File {
|
|||
'--------------------------------------------------------------------------------------------',
|
||||
'Do not edit this file. It is machine generated.'
|
||||
];
|
||||
for (let key of Object.keys(messages)) {
|
||||
for (const key of Object.keys(messages)) {
|
||||
result[key] = messages[key];
|
||||
}
|
||||
|
||||
|
@ -1166,16 +1166,16 @@ export interface TranslationPath {
|
|||
}
|
||||
|
||||
export function prepareI18nPackFiles(externalExtensions: Map<string>, resultingTranslationPaths: TranslationPath[], pseudo = false): NodeJS.ReadWriteStream {
|
||||
let parsePromises: Promise<ParsedXLF[]>[] = [];
|
||||
let mainPack: I18nPack = { version: i18nPackVersion, contents: {} };
|
||||
let extensionsPacks: Map<I18nPack> = {};
|
||||
let errors: any[] = [];
|
||||
const parsePromises: Promise<ParsedXLF[]>[] = [];
|
||||
const mainPack: I18nPack = { version: i18nPackVersion, contents: {} };
|
||||
const extensionsPacks: Map<I18nPack> = {};
|
||||
const errors: any[] = [];
|
||||
return through(function (this: ThroughStream, xlf: File) {
|
||||
let project = path.basename(path.dirname(path.dirname(xlf.relative)));
|
||||
let resource = path.basename(xlf.relative, '.xlf');
|
||||
let contents = xlf.contents.toString();
|
||||
const project = path.basename(path.dirname(path.dirname(xlf.relative)));
|
||||
const resource = path.basename(xlf.relative, '.xlf');
|
||||
const contents = xlf.contents.toString();
|
||||
log(`Found ${project}: ${resource}`);
|
||||
let parsePromise = pseudo ? XLF.parsePseudo(contents) : XLF.parse(contents);
|
||||
const parsePromise = pseudo ? XLF.parsePseudo(contents) : XLF.parse(contents);
|
||||
parsePromises.push(parsePromise);
|
||||
parsePromise.then(
|
||||
resolvedFiles => {
|
||||
|
@ -1213,7 +1213,7 @@ export function prepareI18nPackFiles(externalExtensions: Map<string>, resultingT
|
|||
resultingTranslationPaths.push({ id: 'vscode', resourceName: 'main.i18n.json' });
|
||||
|
||||
this.queue(translatedMainFile);
|
||||
for (let extension in extensionsPacks) {
|
||||
for (const extension in extensionsPacks) {
|
||||
const translatedExtFile = createI18nFile(`extensions/${extension}`, extensionsPacks[extension]);
|
||||
this.queue(translatedExtFile);
|
||||
|
||||
|
@ -1234,16 +1234,16 @@ export function prepareI18nPackFiles(externalExtensions: Map<string>, resultingT
|
|||
}
|
||||
|
||||
export function prepareIslFiles(language: Language, innoSetupConfig: InnoSetup): ThroughStream {
|
||||
let parsePromises: Promise<ParsedXLF[]>[] = [];
|
||||
const parsePromises: Promise<ParsedXLF[]>[] = [];
|
||||
|
||||
return through(function (this: ThroughStream, xlf: File) {
|
||||
let stream = this;
|
||||
let parsePromise = XLF.parse(xlf.contents.toString());
|
||||
const stream = this;
|
||||
const parsePromise = XLF.parse(xlf.contents.toString());
|
||||
parsePromises.push(parsePromise);
|
||||
parsePromise.then(
|
||||
resolvedFiles => {
|
||||
resolvedFiles.forEach(file => {
|
||||
let translatedFile = createIslFile(file.originalFilePath, file.messages, language, innoSetupConfig);
|
||||
const translatedFile = createIslFile(file.originalFilePath, file.messages, language, innoSetupConfig);
|
||||
stream.queue(translatedFile);
|
||||
});
|
||||
}
|
||||
|
@ -1260,7 +1260,7 @@ export function prepareIslFiles(language: Language, innoSetupConfig: InnoSetup):
|
|||
}
|
||||
|
||||
function createIslFile(originalFilePath: string, messages: Map<string>, language: Language, innoSetup: InnoSetup): File {
|
||||
let content: string[] = [];
|
||||
const content: string[] = [];
|
||||
let originalContent: TextModel;
|
||||
if (path.basename(originalFilePath) === 'Default') {
|
||||
originalContent = new TextModel(fs.readFileSync(originalFilePath + '.isl', 'utf8'));
|
||||
|
@ -1269,15 +1269,15 @@ function createIslFile(originalFilePath: string, messages: Map<string>, language
|
|||
}
|
||||
originalContent.lines.forEach(line => {
|
||||
if (line.length > 0) {
|
||||
let firstChar = line.charAt(0);
|
||||
const firstChar = line.charAt(0);
|
||||
if (firstChar === '[' || firstChar === ';') {
|
||||
content.push(line);
|
||||
} else {
|
||||
let sections: string[] = line.split('=');
|
||||
let key = sections[0];
|
||||
const sections: string[] = line.split('=');
|
||||
const key = sections[0];
|
||||
let translated = line;
|
||||
if (key) {
|
||||
let translatedMessage = messages[key];
|
||||
const translatedMessage = messages[key];
|
||||
if (translatedMessage) {
|
||||
translated = `${key}=${translatedMessage}`;
|
||||
}
|
||||
|
@ -1299,9 +1299,9 @@ function createIslFile(originalFilePath: string, messages: Map<string>, language
|
|||
}
|
||||
|
||||
function encodeEntities(value: string): string {
|
||||
let result: string[] = [];
|
||||
const result: string[] = [];
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
let ch = value[i];
|
||||
const ch = value[i];
|
||||
switch (ch) {
|
||||
case '<':
|
||||
result.push('<');
|
||||
|
|
|
@ -40,7 +40,7 @@ function isDeclaration(ts: typeof import('typescript'), a: TSTopLevelDeclare): a
|
|||
function visitTopLevelDeclarations(ts: typeof import('typescript'), sourceFile: ts.SourceFile, visitor: (node: TSTopLevelDeclare) => boolean): void {
|
||||
let stop = false;
|
||||
|
||||
let visit = (node: ts.Node): void => {
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (stop) {
|
||||
return;
|
||||
}
|
||||
|
@ -67,19 +67,19 @@ function visitTopLevelDeclarations(ts: typeof import('typescript'), sourceFile:
|
|||
|
||||
|
||||
function getAllTopLevelDeclarations(ts: typeof import('typescript'), sourceFile: ts.SourceFile): TSTopLevelDeclare[] {
|
||||
let all: TSTopLevelDeclare[] = [];
|
||||
const all: TSTopLevelDeclare[] = [];
|
||||
visitTopLevelDeclarations(ts, sourceFile, (node) => {
|
||||
if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
|
||||
let interfaceDeclaration = <ts.InterfaceDeclaration>node;
|
||||
let triviaStart = interfaceDeclaration.pos;
|
||||
let triviaEnd = interfaceDeclaration.name.pos;
|
||||
let triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
|
||||
const interfaceDeclaration = <ts.InterfaceDeclaration>node;
|
||||
const triviaStart = interfaceDeclaration.pos;
|
||||
const triviaEnd = interfaceDeclaration.name.pos;
|
||||
const triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
|
||||
|
||||
if (triviaText.indexOf('@internal') === -1) {
|
||||
all.push(node);
|
||||
}
|
||||
} else {
|
||||
let nodeText = getNodeText(sourceFile, node);
|
||||
const nodeText = getNodeText(sourceFile, node);
|
||||
if (nodeText.indexOf('@internal') === -1) {
|
||||
all.push(node);
|
||||
}
|
||||
|
@ -118,7 +118,7 @@ function getNodeText(sourceFile: ts.SourceFile, node: { pos: number; end: number
|
|||
function hasModifier(modifiers: ts.NodeArray<ts.Modifier> | undefined, kind: ts.SyntaxKind): boolean {
|
||||
if (modifiers) {
|
||||
for (let i = 0; i < modifiers.length; i++) {
|
||||
let mod = modifiers[i];
|
||||
const mod = modifiers[i];
|
||||
if (mod.kind === kind) {
|
||||
return true;
|
||||
}
|
||||
|
@ -141,7 +141,7 @@ function isDefaultExport(ts: typeof import('typescript'), declaration: ts.Interf
|
|||
function getMassagedTopLevelDeclarationText(ts: typeof import('typescript'), sourceFile: ts.SourceFile, declaration: TSTopLevelDeclare, importName: string, usage: string[], enums: IEnumEntry[]): string {
|
||||
let result = getNodeText(sourceFile, declaration);
|
||||
if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
|
||||
let interfaceDeclaration = <ts.InterfaceDeclaration | ts.ClassDeclaration>declaration;
|
||||
const interfaceDeclaration = <ts.InterfaceDeclaration | ts.ClassDeclaration>declaration;
|
||||
|
||||
const staticTypeName = (
|
||||
isDefaultExport(ts, interfaceDeclaration)
|
||||
|
@ -152,7 +152,7 @@ function getMassagedTopLevelDeclarationText(ts: typeof import('typescript'), sou
|
|||
let instanceTypeName = staticTypeName;
|
||||
const typeParametersCnt = (interfaceDeclaration.typeParameters ? interfaceDeclaration.typeParameters.length : 0);
|
||||
if (typeParametersCnt > 0) {
|
||||
let arr: string[] = [];
|
||||
const arr: string[] = [];
|
||||
for (let i = 0; i < typeParametersCnt; i++) {
|
||||
arr.push('any');
|
||||
}
|
||||
|
@ -162,7 +162,7 @@ function getMassagedTopLevelDeclarationText(ts: typeof import('typescript'), sou
|
|||
const members: ts.NodeArray<ts.ClassElement | ts.TypeElement> = interfaceDeclaration.members;
|
||||
members.forEach((member) => {
|
||||
try {
|
||||
let memberText = getNodeText(sourceFile, member);
|
||||
const memberText = getNodeText(sourceFile, member);
|
||||
if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
|
||||
result = result.replace(memberText, '');
|
||||
} else {
|
||||
|
@ -182,7 +182,7 @@ function getMassagedTopLevelDeclarationText(ts: typeof import('typescript'), sou
|
|||
result = result.replace(/export default /g, 'export ');
|
||||
result = result.replace(/export declare /g, 'export ');
|
||||
result = result.replace(/declare /g, '');
|
||||
let lines = result.split(/\r\n|\r|\n/);
|
||||
const lines = result.split(/\r\n|\r|\n/);
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (/\s*\*/.test(lines[i])) {
|
||||
// very likely a comment
|
||||
|
@ -212,10 +212,10 @@ function format(ts: typeof import('typescript'), text: string, endl: string): st
|
|||
}
|
||||
|
||||
// Parse the source text
|
||||
let sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
|
||||
const sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
|
||||
|
||||
// Get the formatting edits on the input sources
|
||||
let edits = (<any>ts).formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
|
||||
const edits = (<any>ts).formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
|
||||
|
||||
// Apply the edits on the input code
|
||||
return applyEdits(text, edits);
|
||||
|
@ -242,7 +242,7 @@ function format(ts: typeof import('typescript'), text: string, endl: string): st
|
|||
}
|
||||
|
||||
function preformat(text: string, endl: string): string {
|
||||
let lines = text.split(endl);
|
||||
const lines = text.split(endl);
|
||||
let inComment = false;
|
||||
let inCommentDeltaIndent = 0;
|
||||
let indent = 0;
|
||||
|
@ -328,9 +328,9 @@ function format(ts: typeof import('typescript'), text: string, endl: string): st
|
|||
// Apply edits in reverse on the existing text
|
||||
let result = text;
|
||||
for (let i = edits.length - 1; i >= 0; i--) {
|
||||
let change = edits[i];
|
||||
let head = result.slice(0, change.span.start);
|
||||
let tail = result.slice(change.span.start + change.span.length);
|
||||
const change = edits[i];
|
||||
const head = result.slice(0, change.span.start);
|
||||
const tail = result.slice(change.span.start + change.span.length);
|
||||
result = head + change.newText + tail;
|
||||
}
|
||||
return result;
|
||||
|
@ -348,15 +348,15 @@ function createReplacerFromDirectives(directives: [RegExp, string][]): (str: str
|
|||
|
||||
function createReplacer(data: string): (str: string) => string {
|
||||
data = data || '';
|
||||
let rawDirectives = data.split(';');
|
||||
let directives: [RegExp, string][] = [];
|
||||
const rawDirectives = data.split(';');
|
||||
const directives: [RegExp, string][] = [];
|
||||
rawDirectives.forEach((rawDirective) => {
|
||||
if (rawDirective.length === 0) {
|
||||
return;
|
||||
}
|
||||
let pieces = rawDirective.split('=>');
|
||||
const pieces = rawDirective.split('=>');
|
||||
let findStr = pieces[0];
|
||||
let replaceStr = pieces[1];
|
||||
const replaceStr = pieces[1];
|
||||
|
||||
findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
|
||||
findStr = '\\b' + findStr + '\\b';
|
||||
|
@ -380,12 +380,12 @@ interface IEnumEntry {
|
|||
function generateDeclarationFile(ts: typeof import('typescript'), recipe: string, sourceFileGetter: SourceFileGetter): ITempResult | null {
|
||||
const endl = /\r\n/.test(recipe) ? '\r\n' : '\n';
|
||||
|
||||
let lines = recipe.split(endl);
|
||||
let result: string[] = [];
|
||||
const lines = recipe.split(endl);
|
||||
const result: string[] = [];
|
||||
|
||||
let usageCounter = 0;
|
||||
let usageImports: string[] = [];
|
||||
let usage: string[] = [];
|
||||
const usageImports: string[] = [];
|
||||
const usage: string[] = [];
|
||||
|
||||
let failed = false;
|
||||
|
||||
|
@ -393,12 +393,12 @@ function generateDeclarationFile(ts: typeof import('typescript'), recipe: string
|
|||
usage.push(`var b: any;`);
|
||||
|
||||
const generateUsageImport = (moduleId: string) => {
|
||||
let importName = 'm' + (++usageCounter);
|
||||
const importName = 'm' + (++usageCounter);
|
||||
usageImports.push(`import * as ${importName} from './${moduleId.replace(/\.d\.ts$/, '')}';`);
|
||||
return importName;
|
||||
};
|
||||
|
||||
let enums: IEnumEntry[] = [];
|
||||
const enums: IEnumEntry[] = [];
|
||||
let version: string | null = null;
|
||||
|
||||
lines.forEach(line => {
|
||||
|
@ -407,14 +407,14 @@ function generateDeclarationFile(ts: typeof import('typescript'), recipe: string
|
|||
return;
|
||||
}
|
||||
|
||||
let m0 = line.match(/^\/\/dtsv=(\d+)$/);
|
||||
const m0 = line.match(/^\/\/dtsv=(\d+)$/);
|
||||
if (m0) {
|
||||
version = m0[1];
|
||||
}
|
||||
|
||||
let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||
const m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||
if (m1) {
|
||||
let moduleId = m1[1];
|
||||
const moduleId = m1[1];
|
||||
const sourceFile = sourceFileGetter(moduleId);
|
||||
if (!sourceFile) {
|
||||
logErr(`While handling ${line}`);
|
||||
|
@ -425,15 +425,15 @@ function generateDeclarationFile(ts: typeof import('typescript'), recipe: string
|
|||
|
||||
const importName = generateUsageImport(moduleId);
|
||||
|
||||
let replacer = createReplacer(m1[2]);
|
||||
const replacer = createReplacer(m1[2]);
|
||||
|
||||
let typeNames = m1[3].split(/,/);
|
||||
const typeNames = m1[3].split(/,/);
|
||||
typeNames.forEach((typeName) => {
|
||||
typeName = typeName.trim();
|
||||
if (typeName.length === 0) {
|
||||
return;
|
||||
}
|
||||
let declaration = getTopLevelDeclaration(ts, sourceFile, typeName);
|
||||
const declaration = getTopLevelDeclaration(ts, sourceFile, typeName);
|
||||
if (!declaration) {
|
||||
logErr(`While handling ${line}`);
|
||||
logErr(`Cannot find ${typeName}`);
|
||||
|
@ -445,9 +445,9 @@ function generateDeclarationFile(ts: typeof import('typescript'), recipe: string
|
|||
return;
|
||||
}
|
||||
|
||||
let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||
const m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
|
||||
if (m2) {
|
||||
let moduleId = m2[1];
|
||||
const moduleId = m2[1];
|
||||
const sourceFile = sourceFileGetter(moduleId);
|
||||
if (!sourceFile) {
|
||||
logErr(`While handling ${line}`);
|
||||
|
@ -458,11 +458,11 @@ function generateDeclarationFile(ts: typeof import('typescript'), recipe: string
|
|||
|
||||
const importName = generateUsageImport(moduleId);
|
||||
|
||||
let replacer = createReplacer(m2[2]);
|
||||
const replacer = createReplacer(m2[2]);
|
||||
|
||||
let typeNames = m2[3].split(/,/);
|
||||
let typesToExcludeMap: { [typeName: string]: boolean } = {};
|
||||
let typesToExcludeArr: string[] = [];
|
||||
const typeNames = m2[3].split(/,/);
|
||||
const typesToExcludeMap: { [typeName: string]: boolean } = {};
|
||||
const typesToExcludeArr: string[] = [];
|
||||
typeNames.forEach((typeName) => {
|
||||
typeName = typeName.trim();
|
||||
if (typeName.length === 0) {
|
||||
|
@ -479,7 +479,7 @@ function generateDeclarationFile(ts: typeof import('typescript'), recipe: string
|
|||
}
|
||||
} else {
|
||||
// node is ts.VariableStatement
|
||||
let nodeText = getNodeText(sourceFile, declaration);
|
||||
const nodeText = getNodeText(sourceFile, declaration);
|
||||
for (let i = 0; i < typesToExcludeArr.length; i++) {
|
||||
if (nodeText.indexOf(typesToExcludeArr[i]) >= 0) {
|
||||
return;
|
||||
|
@ -732,7 +732,7 @@ class TypeScriptLanguageServiceHost implements ts.LanguageServiceHost {
|
|||
}
|
||||
|
||||
export function execute(): IMonacoDeclarationResult {
|
||||
let r = run3(new DeclarationResolver(new FSProvider()));
|
||||
const r = run3(new DeclarationResolver(new FSProvider()));
|
||||
if (!r) {
|
||||
throw new Error(`monaco.d.ts generation error - Cannot continue`);
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@ import * as tss from './treeshaking';
|
|||
const REPO_ROOT = path.join(__dirname, '../../');
|
||||
const SRC_DIR = path.join(REPO_ROOT, 'src');
|
||||
|
||||
let dirCache: { [dir: string]: boolean } = {};
|
||||
const dirCache: { [dir: string]: boolean } = {};
|
||||
|
||||
function writeFile(filePath: string, contents: Buffer | string): void {
|
||||
function ensureDirs(dirPath: string): void {
|
||||
|
@ -63,13 +63,13 @@ export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: str
|
|||
});
|
||||
}
|
||||
|
||||
let result = tss.shake(options);
|
||||
for (let fileName in result) {
|
||||
const result = tss.shake(options);
|
||||
for (const fileName in result) {
|
||||
if (result.hasOwnProperty(fileName)) {
|
||||
writeFile(path.join(options.destRoot, fileName), result[fileName]);
|
||||
}
|
||||
}
|
||||
let copied: { [fileName: string]: boolean } = {};
|
||||
const copied: { [fileName: string]: boolean } = {};
|
||||
const copyFile = (fileName: string) => {
|
||||
if (copied[fileName]) {
|
||||
return;
|
||||
|
@ -82,7 +82,7 @@ export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: str
|
|||
const writeOutputFile = (fileName: string, contents: string | Buffer) => {
|
||||
writeFile(path.join(options.destRoot, fileName), contents);
|
||||
};
|
||||
for (let fileName in result) {
|
||||
for (const fileName in result) {
|
||||
if (result.hasOwnProperty(fileName)) {
|
||||
const fileContents = result[fileName];
|
||||
const info = ts.preProcessFile(fileContents);
|
||||
|
@ -142,7 +142,7 @@ export function createESMSourcesAndResources2(options: IOptions2): void {
|
|||
const OUT_RESOURCES_FOLDER = path.join(REPO_ROOT, options.outResourcesFolder);
|
||||
|
||||
const getDestAbsoluteFilePath = (file: string): string => {
|
||||
let dest = options.renames[file.replace(/\\/g, '/')] || file;
|
||||
const dest = options.renames[file.replace(/\\/g, '/')] || file;
|
||||
if (dest === 'tsconfig.json') {
|
||||
return path.join(OUT_FOLDER, `tsconfig.json`);
|
||||
}
|
||||
|
@ -229,7 +229,7 @@ export function createESMSourcesAndResources2(options: IOptions2): void {
|
|||
if (dir.charAt(dir.length - 1) !== '/' || dir.charAt(dir.length - 1) !== '\\') {
|
||||
dir += '/';
|
||||
}
|
||||
let result: string[] = [];
|
||||
const result: string[] = [];
|
||||
_walkDirRecursive(dir, result, dir.length);
|
||||
return result;
|
||||
}
|
||||
|
@ -253,7 +253,7 @@ export function createESMSourcesAndResources2(options: IOptions2): void {
|
|||
writeFile(absoluteFilePath, contents);
|
||||
|
||||
function toggleComments(fileContents: string): string {
|
||||
let lines = fileContents.split(/\r\n|\r|\n/);
|
||||
const lines = fileContents.split(/\r\n|\r|\n/);
|
||||
let mode = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
@ -325,14 +325,14 @@ function transportCSS(module: string, enqueue: (module: string) => void, write:
|
|||
|
||||
if (!forceBase64 && /\.svg$/.test(url)) {
|
||||
// .svg => url encode as explained at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
|
||||
let newText = fileContents.toString()
|
||||
const newText = fileContents.toString()
|
||||
.replace(/"/g, '\'')
|
||||
.replace(/</g, '%3C')
|
||||
.replace(/>/g, '%3E')
|
||||
.replace(/&/g, '%26')
|
||||
.replace(/#/g, '%23')
|
||||
.replace(/\s+/g, ' ');
|
||||
let encodedData = ',' + newText;
|
||||
const encodedData = ',' + newText;
|
||||
if (encodedData.length < DATA.length) {
|
||||
DATA = encodedData;
|
||||
}
|
||||
|
|
|
@ -73,7 +73,7 @@ function printDiagnostics(options: ITreeShakingOptions, diagnostics: ReadonlyArr
|
|||
result += `${path.join(options.sourcesRoot, diag.file.fileName)}`;
|
||||
}
|
||||
if (diag.file && diag.start) {
|
||||
let location = diag.file.getLineAndCharacterOfPosition(diag.start);
|
||||
const location = diag.file.getLineAndCharacterOfPosition(diag.start);
|
||||
result += `:${location.line + 1}:${location.character}`;
|
||||
}
|
||||
result += ` - ` + JSON.stringify(diag.messageText);
|
||||
|
@ -216,7 +216,7 @@ function processLibFiles(ts: typeof import('typescript'), options: ITreeShakingO
|
|||
|
||||
// precess dependencies and "recurse"
|
||||
const info = ts.preProcessFile(sourceText);
|
||||
for (let ref of info.libReferenceDirectives) {
|
||||
for (const ref of info.libReferenceDirectives) {
|
||||
stack.push(ref.fileName);
|
||||
}
|
||||
}
|
||||
|
@ -629,7 +629,7 @@ function markNodes(ts: typeof import('typescript'), languageService: ts.Language
|
|||
|
||||
// queue the heritage clauses
|
||||
if (declaration.heritageClauses) {
|
||||
for (let heritageClause of declaration.heritageClauses) {
|
||||
for (const heritageClause of declaration.heritageClauses) {
|
||||
enqueue_black(heritageClause);
|
||||
}
|
||||
}
|
||||
|
@ -682,7 +682,7 @@ function generateResult(ts: typeof import('typescript'), languageService: ts.Lan
|
|||
throw new Error('Could not get program from language service');
|
||||
}
|
||||
|
||||
let result: ITreeShakingResult = {};
|
||||
const result: ITreeShakingResult = {};
|
||||
const writeFile = (filePath: string, contents: string): void => {
|
||||
result[filePath] = contents;
|
||||
};
|
||||
|
@ -700,7 +700,7 @@ function generateResult(ts: typeof import('typescript'), languageService: ts.Lan
|
|||
return;
|
||||
}
|
||||
|
||||
let text = sourceFile.text;
|
||||
const text = sourceFile.text;
|
||||
let result = '';
|
||||
|
||||
function keep(node: ts.Node): void {
|
||||
|
@ -734,7 +734,7 @@ function generateResult(ts: typeof import('typescript'), languageService: ts.Lan
|
|||
return keep(node);
|
||||
}
|
||||
} else {
|
||||
let survivingImports: string[] = [];
|
||||
const survivingImports: string[] = [];
|
||||
for (const importNode of node.importClause.namedBindings.elements) {
|
||||
if (getColor(importNode) === NodeColor.Black) {
|
||||
survivingImports.push(importNode.getFullText(sourceFile));
|
||||
|
@ -762,7 +762,7 @@ function generateResult(ts: typeof import('typescript'), languageService: ts.Lan
|
|||
|
||||
if (ts.isExportDeclaration(node)) {
|
||||
if (node.exportClause && node.moduleSpecifier && ts.isNamedExports(node.exportClause)) {
|
||||
let survivingExports: string[] = [];
|
||||
const survivingExports: string[] = [];
|
||||
for (const exportSpecifier of node.exportClause.elements) {
|
||||
if (getColor(exportSpecifier) === NodeColor.Black) {
|
||||
survivingExports.push(exportSpecifier.getFullText(sourceFile));
|
||||
|
@ -785,8 +785,8 @@ function generateResult(ts: typeof import('typescript'), languageService: ts.Lan
|
|||
continue;
|
||||
}
|
||||
|
||||
let pos = member.pos - node.pos;
|
||||
let end = member.end - node.pos;
|
||||
const pos = member.pos - node.pos;
|
||||
const end = member.end - node.pos;
|
||||
toWrite = toWrite.substring(0, pos) + toWrite.substring(end);
|
||||
}
|
||||
return write(toWrite);
|
||||
|
|
|
@ -117,8 +117,8 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
|
||||
if (/\.d\.ts$/.test(fileName)) {
|
||||
// if it's already a d.ts file just emit it signature
|
||||
let snapshot = host.getScriptSnapshot(fileName);
|
||||
let signature = crypto.createHash('md5')
|
||||
const snapshot = host.getScriptSnapshot(fileName);
|
||||
const signature = crypto.createHash('md5')
|
||||
.update(snapshot.getText(0, snapshot.getLength()))
|
||||
.digest('base64');
|
||||
|
||||
|
@ -129,11 +129,11 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
});
|
||||
}
|
||||
|
||||
let output = service.getEmitOutput(fileName);
|
||||
let files: Vinyl[] = [];
|
||||
const output = service.getEmitOutput(fileName);
|
||||
const files: Vinyl[] = [];
|
||||
let signature: string | undefined;
|
||||
|
||||
for (let file of output.outputFiles) {
|
||||
for (const file of output.outputFiles) {
|
||||
if (!emitSourceMapsInStream && /\.js\.map$/.test(file.name)) {
|
||||
continue;
|
||||
}
|
||||
|
@ -149,22 +149,22 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
}
|
||||
}
|
||||
|
||||
let vinyl = new Vinyl({
|
||||
const vinyl = new Vinyl({
|
||||
path: file.name,
|
||||
contents: Buffer.from(file.text),
|
||||
base: !config._emitWithoutBasePath && baseFor(host.getScriptSnapshot(fileName)) || undefined
|
||||
});
|
||||
|
||||
if (!emitSourceMapsInStream && /\.js$/.test(file.name)) {
|
||||
let sourcemapFile = output.outputFiles.filter(f => /\.js\.map$/.test(f.name))[0];
|
||||
const sourcemapFile = output.outputFiles.filter(f => /\.js\.map$/.test(f.name))[0];
|
||||
|
||||
if (sourcemapFile) {
|
||||
let extname = path.extname(vinyl.relative);
|
||||
let basename = path.basename(vinyl.relative, extname);
|
||||
let dirname = path.dirname(vinyl.relative);
|
||||
let tsname = (dirname === '.' ? '' : dirname + '/') + basename + '.ts';
|
||||
const extname = path.extname(vinyl.relative);
|
||||
const basename = path.basename(vinyl.relative, extname);
|
||||
const dirname = path.dirname(vinyl.relative);
|
||||
const tsname = (dirname === '.' ? '' : dirname + '/') + basename + '.ts';
|
||||
|
||||
let sourceMap = JSON.parse(sourcemapFile.text);
|
||||
const sourceMap = JSON.parse(sourcemapFile.text);
|
||||
sourceMap.sources[0] = tsname.replace(/\\/g, '/');
|
||||
(<any>vinyl).sourceMap = sourceMap;
|
||||
}
|
||||
|
@ -182,17 +182,17 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
});
|
||||
}
|
||||
|
||||
let newErrors: { [path: string]: ts.Diagnostic[] } = Object.create(null);
|
||||
let t1 = Date.now();
|
||||
const newErrors: { [path: string]: ts.Diagnostic[] } = Object.create(null);
|
||||
const t1 = Date.now();
|
||||
|
||||
let toBeEmitted: string[] = [];
|
||||
let toBeCheckedSyntactically: string[] = [];
|
||||
let toBeCheckedSemantically: string[] = [];
|
||||
let filesWithChangedSignature: string[] = [];
|
||||
let dependentFiles: string[] = [];
|
||||
let newLastBuildVersion = new Map<string, string>();
|
||||
const toBeEmitted: string[] = [];
|
||||
const toBeCheckedSyntactically: string[] = [];
|
||||
const toBeCheckedSemantically: string[] = [];
|
||||
const filesWithChangedSignature: string[] = [];
|
||||
const dependentFiles: string[] = [];
|
||||
const newLastBuildVersion = new Map<string, string>();
|
||||
|
||||
for (let fileName of host.getScriptFileNames()) {
|
||||
for (const fileName of host.getScriptFileNames()) {
|
||||
if (lastBuildVersion[fileName] !== host.getScriptVersion(fileName)) {
|
||||
|
||||
toBeEmitted.push(fileName);
|
||||
|
@ -203,8 +203,8 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
|
||||
return new Promise<void>(resolve => {
|
||||
|
||||
let semanticCheckInfo = new Map<string, number>();
|
||||
let seenAsDependentFile = new Set<string>();
|
||||
const semanticCheckInfo = new Map<string, number>();
|
||||
const seenAsDependentFile = new Set<string>();
|
||||
|
||||
function workOnNext() {
|
||||
|
||||
|
@ -221,10 +221,10 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
|
||||
// (1st) emit code
|
||||
else if (toBeEmitted.length) {
|
||||
let fileName = toBeEmitted.pop()!;
|
||||
const fileName = toBeEmitted.pop()!;
|
||||
promise = emitSoon(fileName).then(value => {
|
||||
|
||||
for (let file of value.files) {
|
||||
for (const file of value.files) {
|
||||
_log('[emit code]', file.path);
|
||||
out(file);
|
||||
}
|
||||
|
@ -246,7 +246,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
|
||||
// (2nd) check syntax
|
||||
else if (toBeCheckedSyntactically.length) {
|
||||
let fileName = toBeCheckedSyntactically.pop()!;
|
||||
const fileName = toBeCheckedSyntactically.pop()!;
|
||||
_log('[check syntax]', fileName);
|
||||
promise = checkSyntaxSoon(fileName).then(diagnostics => {
|
||||
delete oldErrors[fileName];
|
||||
|
@ -286,7 +286,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
// (4th) check dependents
|
||||
else if (filesWithChangedSignature.length) {
|
||||
while (filesWithChangedSignature.length) {
|
||||
let fileName = filesWithChangedSignature.pop()!;
|
||||
const fileName = filesWithChangedSignature.pop()!;
|
||||
|
||||
if (!isExternalModule(service.getProgram()!.getSourceFile(fileName)!)) {
|
||||
_log('[check semantics*]', fileName + ' is an internal module and it has changed shape -> check whatever hasn\'t been checked yet');
|
||||
|
@ -308,7 +308,7 @@ export function createTypeScriptBuilder(config: IConfiguration, projectFile: str
|
|||
}
|
||||
if (fileName) {
|
||||
seenAsDependentFile.add(fileName);
|
||||
let value = semanticCheckInfo.get(fileName);
|
||||
const value = semanticCheckInfo.get(fileName);
|
||||
if (value === 0) {
|
||||
// already validated successfully -> look at dependents next
|
||||
host.collectDependents(fileName, dependentFiles);
|
||||
|
@ -507,7 +507,7 @@ class LanguageServiceHost implements ts.LanguageServiceHost {
|
|||
}
|
||||
if (!old || old.getVersion() !== snapshot.getVersion()) {
|
||||
this._dependenciesRecomputeList.push(filename);
|
||||
let node = this._dependencies.lookup(filename);
|
||||
const node = this._dependencies.lookup(filename);
|
||||
if (node) {
|
||||
node.outgoing = Object.create(null);
|
||||
}
|
||||
|
@ -605,7 +605,7 @@ class LanguageServiceHost implements ts.LanguageServiceHost {
|
|||
}
|
||||
|
||||
if (!found) {
|
||||
for (let key in this._fileNameToDeclaredModule) {
|
||||
for (const key in this._fileNameToDeclaredModule) {
|
||||
if (this._fileNameToDeclaredModule[key] && ~this._fileNameToDeclaredModule[key].indexOf(ref.fileName)) {
|
||||
this._dependencies.inertEdge(filename, key);
|
||||
}
|
||||
|
|
|
@ -89,7 +89,7 @@ export function create(
|
|||
const result = (token: builder.CancellationToken) => createStream(token);
|
||||
result.src = (opts?: { cwd?: string; base?: string }) => {
|
||||
let _pos = 0;
|
||||
let _fileNames = cmdLine.fileNames.slice(0);
|
||||
const _fileNames = cmdLine.fileNames.slice(0);
|
||||
return new class extends Readable {
|
||||
constructor() {
|
||||
super({ objectMode: true });
|
||||
|
|
|
@ -28,7 +28,7 @@ export module collections {
|
|||
}
|
||||
|
||||
export function forEach<T>(collection: { [keys: string]: T }, callback: (entry: { key: string; value: T }) => void): void {
|
||||
for (let key in collection) {
|
||||
for (const key in collection) {
|
||||
if (hasOwnProperty.call(collection, key)) {
|
||||
callback({
|
||||
key: key,
|
||||
|
|
|
@ -306,7 +306,7 @@ function _rreaddir(dirPath: string, prepend: string, result: string[]): void {
|
|||
}
|
||||
|
||||
export function rreddir(dirPath: string): string[] {
|
||||
let result: string[] = [];
|
||||
const result: string[] = [];
|
||||
_rreaddir(dirPath, '', result);
|
||||
return result;
|
||||
}
|
||||
|
@ -423,7 +423,7 @@ export function createExternalLoaderConfig(webEndpoint?: string, commit?: string
|
|||
return undefined;
|
||||
}
|
||||
webEndpoint = webEndpoint + `/${quality}/${commit}`;
|
||||
let nodePaths = acquireWebNodePaths();
|
||||
const nodePaths = acquireWebNodePaths();
|
||||
Object.keys(nodePaths).map(function (key, _) {
|
||||
nodePaths[key] = `${webEndpoint}/node_modules/${key}/${nodePaths[key]}`;
|
||||
});
|
||||
|
|
|
@ -43,14 +43,14 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
|
||||
const customDataSource = getCustomDataSource(context.subscriptions);
|
||||
|
||||
let documentSelector = ['css', 'scss', 'less'];
|
||||
const documentSelector = ['css', 'scss', 'less'];
|
||||
|
||||
const formatterRegistrations: FormatterRegistration[] = documentSelector.map(languageId => ({
|
||||
languageId, settingId: `${languageId}.format.enable`, provider: undefined
|
||||
}));
|
||||
|
||||
// Options to control the language client
|
||||
let clientOptions: LanguageClientOptions = {
|
||||
const clientOptions: LanguageClientOptions = {
|
||||
documentSelector,
|
||||
synchronize: {
|
||||
configurationSection: ['css', 'scss', 'less']
|
||||
|
@ -98,7 +98,7 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
};
|
||||
|
||||
// Create the language client and start the client.
|
||||
let client = newLanguageClient('css', localize('cssserver.name', 'CSS Language Server'), clientOptions);
|
||||
const client = newLanguageClient('css', localize('cssserver.name', 'CSS Language Server'), clientOptions);
|
||||
client.registerProposedFeatures();
|
||||
|
||||
await client.start();
|
||||
|
@ -125,17 +125,17 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
|
||||
return languages.registerCompletionItemProvider(documentSelector, {
|
||||
provideCompletionItems(doc: TextDocument, pos: Position) {
|
||||
let lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos));
|
||||
let match = lineUntilPos.match(regionCompletionRegExpr);
|
||||
const lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos));
|
||||
const match = lineUntilPos.match(regionCompletionRegExpr);
|
||||
if (match) {
|
||||
let range = new Range(new Position(pos.line, match[1].length), pos);
|
||||
let beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet);
|
||||
const range = new Range(new Position(pos.line, match[1].length), pos);
|
||||
const beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet);
|
||||
beginProposal.range = range; TextEdit.replace(range, '/* #region */');
|
||||
beginProposal.insertText = new SnippetString('/* #region $1*/');
|
||||
beginProposal.documentation = localize('folding.start', 'Folding Region Start');
|
||||
beginProposal.filterText = match[2];
|
||||
beginProposal.sortText = 'za';
|
||||
let endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet);
|
||||
const endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet);
|
||||
endProposal.range = range;
|
||||
endProposal.insertText = '/* #endregion */';
|
||||
endProposal.documentation = localize('folding.end', 'Folding Region End');
|
||||
|
@ -151,13 +151,13 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
commands.registerCommand('_css.applyCodeAction', applyCodeAction);
|
||||
|
||||
function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) {
|
||||
let textEditor = window.activeTextEditor;
|
||||
const textEditor = window.activeTextEditor;
|
||||
if (textEditor && textEditor.document.uri.toString() === uri) {
|
||||
if (textEditor.document.version !== documentVersion) {
|
||||
window.showInformationMessage(`CSS fix is outdated and can't be applied to the document.`);
|
||||
}
|
||||
textEditor.edit(mutator => {
|
||||
for (let edit of edits) {
|
||||
for (const edit of edits) {
|
||||
mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText);
|
||||
}
|
||||
}).then(success => {
|
||||
|
|
|
@ -18,10 +18,10 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
let cleanupInterval: NodeJS.Timer | undefined = undefined;
|
||||
if (cleanupIntervalTimeInSec > 0) {
|
||||
cleanupInterval = setInterval(() => {
|
||||
let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
|
||||
let uris = Object.keys(languageModels);
|
||||
for (let uri of uris) {
|
||||
let languageModelInfo = languageModels[uri];
|
||||
const cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
|
||||
const uris = Object.keys(languageModels);
|
||||
for (const uri of uris) {
|
||||
const languageModelInfo = languageModels[uri];
|
||||
if (languageModelInfo.cTime < cutoffTime) {
|
||||
delete languageModels[uri];
|
||||
nModels--;
|
||||
|
@ -32,14 +32,14 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
|
||||
return {
|
||||
get(document: TextDocument): T {
|
||||
let version = document.version;
|
||||
let languageId = document.languageId;
|
||||
let languageModelInfo = languageModels[document.uri];
|
||||
const version = document.version;
|
||||
const languageId = document.languageId;
|
||||
const languageModelInfo = languageModels[document.uri];
|
||||
if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
|
||||
languageModelInfo.cTime = Date.now();
|
||||
return languageModelInfo.languageModel;
|
||||
}
|
||||
let languageModel = parse(document);
|
||||
const languageModel = parse(document);
|
||||
languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
|
||||
if (!languageModelInfo) {
|
||||
nModels++;
|
||||
|
@ -48,8 +48,8 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
if (nModels === maxEntries) {
|
||||
let oldestTime = Number.MAX_VALUE;
|
||||
let oldestUri = null;
|
||||
for (let uri in languageModels) {
|
||||
let languageModelInfo = languageModels[uri];
|
||||
for (const uri in languageModels) {
|
||||
const languageModelInfo = languageModels[uri];
|
||||
if (languageModelInfo.cTime < oldestTime) {
|
||||
oldestUri = uri;
|
||||
oldestTime = languageModelInfo.cTime;
|
||||
|
@ -64,7 +64,7 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
|
||||
},
|
||||
onDocumentRemoved(document: TextDocument) {
|
||||
let uri = document.uri;
|
||||
const uri = document.uri;
|
||||
if (languageModels[uri]) {
|
||||
delete languageModels[uri];
|
||||
nModels--;
|
||||
|
|
|
@ -65,7 +65,7 @@ export interface RequestService {
|
|||
|
||||
export function getRequestService(handledSchemas: string[], connection: Connection, runtime: RuntimeEnvironment): RequestService {
|
||||
const builtInHandlers: { [protocol: string]: RequestService | undefined } = {};
|
||||
for (let protocol of handledSchemas) {
|
||||
for (const protocol of handledSchemas) {
|
||||
if (protocol === 'file') {
|
||||
builtInHandlers[protocol] = runtime.file;
|
||||
} else if (protocol === 'http' || protocol === 'https') {
|
||||
|
|
|
@ -19,13 +19,13 @@ export interface ItemDescription {
|
|||
|
||||
suite('Completions', () => {
|
||||
|
||||
let assertCompletion = function (completions: CompletionList, expected: ItemDescription, document: TextDocument, _offset: number) {
|
||||
let matches = completions.items.filter(completion => {
|
||||
const assertCompletion = function (completions: CompletionList, expected: ItemDescription, document: TextDocument, _offset: number) {
|
||||
const matches = completions.items.filter(completion => {
|
||||
return completion.label === expected.label;
|
||||
});
|
||||
|
||||
assert.strictEqual(matches.length, 1, `${expected.label} should only existing once: Actual: ${completions.items.map(c => c.label).join(', ')}`);
|
||||
let match = matches[0];
|
||||
const match = matches[0];
|
||||
if (expected.resultText && TextEdit.is(match.textEdit)) {
|
||||
assert.strictEqual(TextDocument.applyEdits(document, [match.textEdit]), expected.resultText);
|
||||
}
|
||||
|
@ -47,21 +47,21 @@ suite('Completions', () => {
|
|||
|
||||
const context = getDocumentContext(testUri, workspaceFolders);
|
||||
const stylesheet = cssLanguageService.parseStylesheet(document);
|
||||
let list = await cssLanguageService.doComplete2(document, position, stylesheet, context);
|
||||
const list = await cssLanguageService.doComplete2(document, position, stylesheet, context);
|
||||
|
||||
if (expected.count) {
|
||||
assert.strictEqual(list.items.length, expected.count);
|
||||
}
|
||||
if (expected.items) {
|
||||
for (let item of expected.items) {
|
||||
for (const item of expected.items) {
|
||||
assertCompletion(list, item, document, offset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
test('CSS url() Path completion', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
await assertCompletions('html { background-image: url("./|")', {
|
||||
items: [
|
||||
|
@ -119,8 +119,8 @@ suite('Completions', () => {
|
|||
});
|
||||
|
||||
test('CSS url() Path Completion - Unquoted url', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
await assertCompletions('html { background-image: url(./|)', {
|
||||
items: [
|
||||
|
@ -148,8 +148,8 @@ suite('Completions', () => {
|
|||
});
|
||||
|
||||
test('CSS @import Path completion', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
await assertCompletions(`@import './|'`, {
|
||||
items: [
|
||||
|
@ -171,8 +171,8 @@ suite('Completions', () => {
|
|||
* For SCSS, `@import 'foo';` can be used for importing partial file `_foo.scss`
|
||||
*/
|
||||
test('SCSS @import Path completion', async function () {
|
||||
let testCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
const testCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
/**
|
||||
* We are in a CSS file, so no special treatment for SCSS partial files
|
||||
|
@ -184,7 +184,7 @@ suite('Completions', () => {
|
|||
]
|
||||
}, testCSSUri, folders);
|
||||
|
||||
let testSCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/scss/main.scss')).toString();
|
||||
const testSCSSUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/scss/main.scss')).toString();
|
||||
await assertCompletions(`@import './|'`, {
|
||||
items: [
|
||||
{ label: '_foo.scss', resultText: `@import './foo'` }
|
||||
|
@ -193,8 +193,8 @@ suite('Completions', () => {
|
|||
});
|
||||
|
||||
test('Completion should ignore files/folders starting with dot', async function () {
|
||||
let testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
let folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
const testUri = URI.file(path.resolve(__dirname, '../../test/pathCompletionFixtures/about/about.css')).toString();
|
||||
const folders = [{ name: 'x', uri: URI.file(path.resolve(__dirname, '../../test')).toString() }];
|
||||
|
||||
await assertCompletions('html { background-image: url("../|")', {
|
||||
count: 4
|
||||
|
|
|
@ -21,13 +21,13 @@ export interface ItemDescription {
|
|||
suite('Links', () => {
|
||||
const cssLanguageService = getCSSLanguageService({ fileSystemProvider: getNodeFSRequestService() });
|
||||
|
||||
let assertLink = function (links: DocumentLink[], expected: ItemDescription, document: TextDocument) {
|
||||
let matches = links.filter(link => {
|
||||
const assertLink = function (links: DocumentLink[], expected: ItemDescription, document: TextDocument) {
|
||||
const matches = links.filter(link => {
|
||||
return document.offsetAt(link.range.start) === expected.offset;
|
||||
});
|
||||
|
||||
assert.strictEqual(matches.length, 1, `${expected.offset} should only existing once: Actual: ${links.map(l => document.offsetAt(l.range.start)).join(', ')}`);
|
||||
let match = matches[0];
|
||||
const match = matches[0];
|
||||
assert.strictEqual(document.getText(match.range), expected.value);
|
||||
assert.strictEqual(match.target, expected.target);
|
||||
};
|
||||
|
@ -45,11 +45,11 @@ suite('Links', () => {
|
|||
const context = getDocumentContext(testUri, workspaceFolders);
|
||||
|
||||
const stylesheet = cssLanguageService.parseStylesheet(document);
|
||||
let links = await cssLanguageService.findDocumentLinks2(document, stylesheet, context)!;
|
||||
const links = await cssLanguageService.findDocumentLinks2(document, stylesheet, context)!;
|
||||
|
||||
assert.strictEqual(links.length, expected.length);
|
||||
|
||||
for (let item of expected) {
|
||||
for (const item of expected) {
|
||||
assertLink(links, item, document);
|
||||
}
|
||||
}
|
||||
|
@ -60,8 +60,8 @@ suite('Links', () => {
|
|||
|
||||
test('url links', async function () {
|
||||
|
||||
let testUri = getTestResource('about.css');
|
||||
let folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
const testUri = getTestResource('about.css');
|
||||
const folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
|
||||
await assertLinks('html { background-image: url("hello.html|")',
|
||||
[{ offset: 29, value: '"hello.html"', target: getTestResource('hello.html') }], testUri, folders
|
||||
|
@ -70,8 +70,8 @@ suite('Links', () => {
|
|||
|
||||
test('node module resolving', async function () {
|
||||
|
||||
let testUri = getTestResource('about.css');
|
||||
let folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
const testUri = getTestResource('about.css');
|
||||
const folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
|
||||
await assertLinks('html { background-image: url("~foo/hello.html|")',
|
||||
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
|
||||
|
@ -80,8 +80,8 @@ suite('Links', () => {
|
|||
|
||||
test('node module subfolder resolving', async function () {
|
||||
|
||||
let testUri = getTestResource('subdir/about.css');
|
||||
let folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
const testUri = getTestResource('subdir/about.css');
|
||||
const folders = [{ name: 'x', uri: getTestResource('') }];
|
||||
|
||||
await assertLinks('html { background-image: url("~foo/hello.html|")',
|
||||
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
|
||||
|
|
|
@ -10,7 +10,7 @@ import { Utils, URI } from 'vscode-uri';
|
|||
|
||||
export function getDocumentContext(documentUri: string, workspaceFolders: WorkspaceFolder[]): DocumentContext {
|
||||
function getRootFolder(): string | undefined {
|
||||
for (let folder of workspaceFolders) {
|
||||
for (const folder of workspaceFolders) {
|
||||
let folderURI = folder.uri;
|
||||
if (!endsWith(folderURI, '/')) {
|
||||
folderURI = folderURI + '/';
|
||||
|
@ -25,7 +25,7 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
|
|||
return {
|
||||
resolveReference: (ref: string, base = documentUri) => {
|
||||
if (ref[0] === '/') { // resolve absolute path against the current workspace folder
|
||||
let folderUri = getRootFolder();
|
||||
const folderUri = getRootFolder();
|
||||
if (folderUri) {
|
||||
return folderUri + ref.substr(1);
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import { RuntimeEnvironment } from '../cssServer';
|
|||
|
||||
export function formatError(message: string, err: any): string {
|
||||
if (err instanceof Error) {
|
||||
let error = <Error>err;
|
||||
const error = <Error>err;
|
||||
return `${message}: ${error.message}\n${error.stack}`;
|
||||
} else if (typeof err === 'string') {
|
||||
return `${message}: ${err}`;
|
||||
|
|
|
@ -21,7 +21,7 @@ export function startsWith(haystack: string, needle: string): boolean {
|
|||
* Determines if haystack ends with needle.
|
||||
*/
|
||||
export function endsWith(haystack: string, needle: string): boolean {
|
||||
let diff = haystack.length - needle.length;
|
||||
const diff = haystack.length - needle.length;
|
||||
if (diff > 0) {
|
||||
return haystack.lastIndexOf(needle) === diff;
|
||||
} else if (diff === 0) {
|
||||
|
|
|
@ -243,7 +243,7 @@ const createServerInner = async (ipcAddress: string) => {
|
|||
const createServerInstance = (ipcAddress: string) =>
|
||||
new Promise<Server>((resolve, reject) => {
|
||||
const s = createServer(socket => {
|
||||
let data: Buffer[] = [];
|
||||
const data: Buffer[] = [];
|
||||
socket.on('data', async chunk => {
|
||||
if (chunk[chunk.length - 1] !== 0) {
|
||||
// terminated with NUL byte
|
||||
|
@ -392,7 +392,7 @@ async function getIpcAddress(context: vscode.ExtensionContext) {
|
|||
}
|
||||
|
||||
function getJsDebugSettingKey() {
|
||||
let o: { [key: string]: unknown } = {};
|
||||
const o: { [key: string]: unknown } = {};
|
||||
const config = vscode.workspace.getConfiguration(SETTING_SECTION);
|
||||
for (const setting of SETTINGS_CAUSE_REFRESH) {
|
||||
o[setting] = config.get(setting);
|
||||
|
|
|
@ -57,7 +57,7 @@ class ServerReadyDetector extends vscode.Disposable {
|
|||
}
|
||||
|
||||
static stop(session: vscode.DebugSession): void {
|
||||
let detector = ServerReadyDetector.detectors.get(session);
|
||||
const detector = ServerReadyDetector.detectors.get(session);
|
||||
if (detector) {
|
||||
ServerReadyDetector.detectors.delete(session);
|
||||
detector.dispose();
|
||||
|
@ -65,7 +65,7 @@ class ServerReadyDetector extends vscode.Disposable {
|
|||
}
|
||||
|
||||
static rememberShellPid(session: vscode.DebugSession, pid: number) {
|
||||
let detector = ServerReadyDetector.detectors.get(session);
|
||||
const detector = ServerReadyDetector.detectors.get(session);
|
||||
if (detector) {
|
||||
detector.shellPid = pid;
|
||||
}
|
||||
|
@ -77,7 +77,7 @@ class ServerReadyDetector extends vscode.Disposable {
|
|||
|
||||
// first find the detector with a matching pid
|
||||
const pid = await e.terminal.processId;
|
||||
for (let [, detector] of this.detectors) {
|
||||
for (const [, detector] of this.detectors) {
|
||||
if (detector.shellPid === pid) {
|
||||
detector.detectPattern(e.data);
|
||||
return;
|
||||
|
@ -85,7 +85,7 @@ class ServerReadyDetector extends vscode.Disposable {
|
|||
}
|
||||
|
||||
// if none found, try all detectors until one matches
|
||||
for (let [, detector] of this.detectors) {
|
||||
for (const [, detector] of this.detectors) {
|
||||
if (detector.detectPattern(e.data)) {
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -49,7 +49,7 @@ export class DefaultCompletionItemProvider implements vscode.CompletionItemProvi
|
|||
|
||||
const mappedLanguages = getMappingForIncludedLanguages();
|
||||
const isSyntaxMapped = mappedLanguages[document.languageId] ? true : false;
|
||||
let emmetMode = getEmmetMode((isSyntaxMapped ? mappedLanguages[document.languageId] : document.languageId), mappedLanguages, excludedLanguages);
|
||||
const emmetMode = getEmmetMode((isSyntaxMapped ? mappedLanguages[document.languageId] : document.languageId), mappedLanguages, excludedLanguages);
|
||||
|
||||
if (!emmetMode
|
||||
|| emmetConfig['showExpandedAbbreviation'] === 'never'
|
||||
|
@ -135,7 +135,7 @@ export class DefaultCompletionItemProvider implements vscode.CompletionItemProvi
|
|||
const offset = document.offsetAt(position);
|
||||
if (isStyleSheet(document.languageId) && context.triggerKind !== vscode.CompletionTriggerKind.TriggerForIncompleteCompletions) {
|
||||
validateLocation = true;
|
||||
let usePartialParsing = vscode.workspace.getConfiguration('emmet')['optimizeStylesheetParsing'] === true;
|
||||
const usePartialParsing = vscode.workspace.getConfiguration('emmet')['optimizeStylesheetParsing'] === true;
|
||||
rootNode = usePartialParsing && document.lineCount > 1000 ? parsePartialStylesheet(document, position) : <Stylesheet>getRootNode(document, true);
|
||||
if (!rootNode) {
|
||||
return;
|
||||
|
@ -152,8 +152,8 @@ export class DefaultCompletionItemProvider implements vscode.CompletionItemProvi
|
|||
if (!rootNode) {
|
||||
return;
|
||||
}
|
||||
let flatNode = getFlatNode(rootNode, offset, true);
|
||||
let embeddedCssNode = getEmbeddedCssNodeIfAny(document, flatNode, position);
|
||||
const flatNode = getFlatNode(rootNode, offset, true);
|
||||
const embeddedCssNode = getEmbeddedCssNodeIfAny(document, flatNode, position);
|
||||
currentNode = getFlatNode(embeddedCssNode, offset, true);
|
||||
}
|
||||
|
||||
|
@ -167,7 +167,7 @@ export class DefaultCompletionItemProvider implements vscode.CompletionItemProvi
|
|||
// Check for document symbols in js/ts/jsx/tsx and avoid triggering emmet for abbreviations of the form symbolName.sometext
|
||||
// Presence of > or * or + in the abbreviation denotes valid abbreviation that should trigger emmet
|
||||
if (!isStyleSheet(syntax) && (document.languageId === 'javascript' || document.languageId === 'javascriptreact' || document.languageId === 'typescript' || document.languageId === 'typescriptreact')) {
|
||||
let abbreviation: string = extractAbbreviationResults.abbreviation;
|
||||
const abbreviation: string = extractAbbreviationResults.abbreviation;
|
||||
// For the second condition, we don't want abbreviations that have [] characters but not ='s in them to expand
|
||||
// In turn, users must explicitly expand abbreviations of the form Component[attr1 attr2], but it means we don't try to expand a[i].
|
||||
if (abbreviation.startsWith('this.') || /\[[^\]=]*\]/.test(abbreviation)) {
|
||||
|
@ -194,14 +194,14 @@ export class DefaultCompletionItemProvider implements vscode.CompletionItemProvi
|
|||
}
|
||||
}
|
||||
|
||||
let newItems: vscode.CompletionItem[] = [];
|
||||
const newItems: vscode.CompletionItem[] = [];
|
||||
if (result && result.items) {
|
||||
result.items.forEach((item: any) => {
|
||||
let newItem = new vscode.CompletionItem(item.label);
|
||||
const newItem = new vscode.CompletionItem(item.label);
|
||||
newItem.documentation = item.documentation;
|
||||
newItem.detail = item.detail;
|
||||
newItem.insertText = new vscode.SnippetString(item.textEdit.newText);
|
||||
let oldrange = item.textEdit.range;
|
||||
const oldrange = item.textEdit.range;
|
||||
newItem.range = new vscode.Range(oldrange.start.line, oldrange.start.character, oldrange.end.line, oldrange.end.character);
|
||||
|
||||
newItem.filterText = item.filterText;
|
||||
|
|
|
@ -12,9 +12,9 @@ export function fetchEditPoint(direction: string): void {
|
|||
}
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
|
||||
let newSelections: vscode.Selection[] = [];
|
||||
const newSelections: vscode.Selection[] = [];
|
||||
editor.selections.forEach(selection => {
|
||||
let updatedSelection = direction === 'next' ? nextEditPoint(selection, editor) : prevEditPoint(selection, editor);
|
||||
const updatedSelection = direction === 'next' ? nextEditPoint(selection, editor) : prevEditPoint(selection, editor);
|
||||
newSelections.push(updatedSelection);
|
||||
});
|
||||
editor.selections = newSelections;
|
||||
|
@ -23,7 +23,7 @@ export function fetchEditPoint(direction: string): void {
|
|||
|
||||
function nextEditPoint(selection: vscode.Selection, editor: vscode.TextEditor): vscode.Selection {
|
||||
for (let lineNum = selection.anchor.line; lineNum < editor.document.lineCount; lineNum++) {
|
||||
let updatedSelection = findEditPoint(lineNum, editor, selection.anchor, 'next');
|
||||
const updatedSelection = findEditPoint(lineNum, editor, selection.anchor, 'next');
|
||||
if (updatedSelection) {
|
||||
return updatedSelection;
|
||||
}
|
||||
|
@ -33,7 +33,7 @@ function nextEditPoint(selection: vscode.Selection, editor: vscode.TextEditor):
|
|||
|
||||
function prevEditPoint(selection: vscode.Selection, editor: vscode.TextEditor): vscode.Selection {
|
||||
for (let lineNum = selection.anchor.line; lineNum >= 0; lineNum--) {
|
||||
let updatedSelection = findEditPoint(lineNum, editor, selection.anchor, 'prev');
|
||||
const updatedSelection = findEditPoint(lineNum, editor, selection.anchor, 'prev');
|
||||
if (updatedSelection) {
|
||||
return updatedSelection;
|
||||
}
|
||||
|
@ -43,7 +43,7 @@ function prevEditPoint(selection: vscode.Selection, editor: vscode.TextEditor):
|
|||
|
||||
|
||||
function findEditPoint(lineNum: number, editor: vscode.TextEditor, position: vscode.Position, direction: string): vscode.Selection | undefined {
|
||||
let line = editor.document.lineAt(lineNum);
|
||||
const line = editor.document.lineAt(lineNum);
|
||||
let lineContent = line.text;
|
||||
|
||||
if (lineNum !== position.line && line.isEmptyOrWhitespace && lineContent.length) {
|
||||
|
@ -53,8 +53,8 @@ function findEditPoint(lineNum: number, editor: vscode.TextEditor, position: vsc
|
|||
if (lineNum === position.line && direction === 'prev') {
|
||||
lineContent = lineContent.substr(0, position.character);
|
||||
}
|
||||
let emptyAttrIndex = direction === 'next' ? lineContent.indexOf('""', lineNum === position.line ? position.character : 0) : lineContent.lastIndexOf('""');
|
||||
let emptyTagIndex = direction === 'next' ? lineContent.indexOf('><', lineNum === position.line ? position.character : 0) : lineContent.lastIndexOf('><');
|
||||
const emptyAttrIndex = direction === 'next' ? lineContent.indexOf('""', lineNum === position.line ? position.character : 0) : lineContent.lastIndexOf('""');
|
||||
const emptyTagIndex = direction === 'next' ? lineContent.indexOf('><', lineNum === position.line ? position.character : 0) : lineContent.lastIndexOf('><');
|
||||
|
||||
let winner = -1;
|
||||
|
||||
|
|
|
@ -161,8 +161,8 @@ const languageMappingForCompletionProviders: Map<string, string> = new Map<strin
|
|||
const completionProvidersMapping: Map<string, vscode.Disposable> = new Map<string, vscode.Disposable>();
|
||||
|
||||
function registerCompletionProviders(context: vscode.ExtensionContext) {
|
||||
let completionProvider = new DefaultCompletionItemProvider();
|
||||
let includedLanguages = getMappingForIncludedLanguages();
|
||||
const completionProvider = new DefaultCompletionItemProvider();
|
||||
const includedLanguages = getMappingForIncludedLanguages();
|
||||
|
||||
Object.keys(includedLanguages).forEach(language => {
|
||||
if (languageMappingForCompletionProviders.has(language) && languageMappingForCompletionProviders.get(language) === includedLanguages[language]) {
|
||||
|
|
|
@ -21,7 +21,7 @@ export function incrementDecrement(delta: number): Thenable<boolean> | undefined
|
|||
|
||||
return editor.edit(editBuilder => {
|
||||
editor.selections.forEach(selection => {
|
||||
let rangeToReplace = locate(editor.document, selection.isReversed ? selection.anchor : selection.active);
|
||||
const rangeToReplace = locate(editor.document, selection.isReversed ? selection.anchor : selection.active);
|
||||
if (!rangeToReplace) {
|
||||
return;
|
||||
}
|
||||
|
@ -40,7 +40,7 @@ export function incrementDecrement(delta: number): Thenable<boolean> | undefined
|
|||
*/
|
||||
export function update(numString: string, delta: number): string {
|
||||
let m: RegExpMatchArray | null;
|
||||
let decimals = (m = numString.match(/\.(\d+)$/)) ? m[1].length : 1;
|
||||
const decimals = (m = numString.match(/\.(\d+)$/)) ? m[1].length : 1;
|
||||
let output = String((parseFloat(numString) + delta).toFixed(decimals)).replace(/\.0+$/, '');
|
||||
|
||||
if (m = numString.match(/^\-?(0\d+)/)) {
|
||||
|
|
|
@ -20,7 +20,7 @@ export function matchTag() {
|
|||
return;
|
||||
}
|
||||
|
||||
let updatedSelections: vscode.Selection[] = [];
|
||||
const updatedSelections: vscode.Selection[] = [];
|
||||
editor.selections.forEach(selection => {
|
||||
const updatedSelection = getUpdatedSelections(document, rootNode, selection.start);
|
||||
if (updatedSelection) {
|
||||
|
|
|
@ -19,7 +19,7 @@ export function removeTag() {
|
|||
return;
|
||||
}
|
||||
|
||||
let finalRangesToRemove = Array.from(editor.selections).reverse()
|
||||
const finalRangesToRemove = Array.from(editor.selections).reverse()
|
||||
.reduce<vscode.Range[]>((prev, selection) =>
|
||||
prev.concat(getRangesToRemove(editor.document, rootNode, selection)), []);
|
||||
|
||||
|
@ -68,7 +68,7 @@ function getRangesToRemove(document: vscode.TextDocument, rootNode: HtmlFlatNode
|
|||
}
|
||||
}
|
||||
|
||||
let rangesToRemove = [];
|
||||
const rangesToRemove = [];
|
||||
if (openTagRange) {
|
||||
rangesToRemove.push(openTagRange);
|
||||
if (closeTagRange) {
|
||||
|
|
|
@ -21,7 +21,7 @@ export function fetchSelectItem(direction: string): void {
|
|||
return;
|
||||
}
|
||||
|
||||
let newSelections: vscode.Selection[] = [];
|
||||
const newSelections: vscode.Selection[] = [];
|
||||
editor.selections.forEach(selection => {
|
||||
const selectionStart = selection.isReversed ? selection.active : selection.anchor;
|
||||
const selectionEnd = selection.isReversed ? selection.anchor : selection.active;
|
||||
|
|
|
@ -28,7 +28,7 @@ export function nextItemStylesheet(document: vscode.TextDocument, startPosition:
|
|||
if (currentNode.type === 'property' &&
|
||||
startOffset >= (<Property>currentNode).valueToken.start &&
|
||||
endOffset <= (<Property>currentNode).valueToken.end) {
|
||||
let singlePropertyValue = getSelectionFromProperty(document, currentNode, startOffset, endOffset, false, 'next');
|
||||
const singlePropertyValue = getSelectionFromProperty(document, currentNode, startOffset, endOffset, false, 'next');
|
||||
if (singlePropertyValue) {
|
||||
return singlePropertyValue;
|
||||
}
|
||||
|
@ -77,7 +77,7 @@ export function prevItemStylesheet(document: vscode.TextDocument, startPosition:
|
|||
if (currentNode.type === 'property' &&
|
||||
startOffset >= (<Property>currentNode).valueToken.start &&
|
||||
endOffset <= (<Property>currentNode).valueToken.end) {
|
||||
let singlePropertyValue = getSelectionFromProperty(document, currentNode, startOffset, endOffset, false, 'prev');
|
||||
const singlePropertyValue = getSelectionFromProperty(document, currentNode, startOffset, endOffset, false, 'prev');
|
||||
if (singlePropertyValue) {
|
||||
return singlePropertyValue;
|
||||
}
|
||||
|
@ -115,7 +115,7 @@ function getSelectionFromProperty(document: vscode.TextDocument, node: Node | un
|
|||
}
|
||||
const propertyNode = <Property>node;
|
||||
|
||||
let propertyValue = propertyNode.valueToken.stream.substring(propertyNode.valueToken.start, propertyNode.valueToken.end);
|
||||
const propertyValue = propertyNode.valueToken.stream.substring(propertyNode.valueToken.start, propertyNode.valueToken.end);
|
||||
selectFullValue = selectFullValue ||
|
||||
(direction === 'prev' && selectionStart === propertyNode.valueToken.start && selectionEnd < propertyNode.valueToken.end);
|
||||
|
||||
|
@ -144,7 +144,7 @@ function getSelectionFromProperty(document: vscode.TextDocument, node: Node | un
|
|||
}
|
||||
|
||||
|
||||
let [newSelectionStartOffset, newSelectionEndOffset] = direction === 'prev' ? findPrevWord(propertyValue, pos) : findNextWord(propertyValue, pos);
|
||||
const [newSelectionStartOffset, newSelectionEndOffset] = direction === 'prev' ? findPrevWord(propertyValue, pos) : findNextWord(propertyValue, pos);
|
||||
if (!newSelectionStartOffset && !newSelectionEndOffset) {
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -62,13 +62,13 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(htmlContents, '.html', (editor, _) => {
|
||||
editor.selections = [new Selection(1, 5, 1, 5)];
|
||||
|
||||
let expectedNextEditPoints: [number, number][] = [[4, 16], [6, 8], [10, 2], [10, 2]];
|
||||
const expectedNextEditPoints: [number, number][] = [[4, 16], [6, 8], [10, 2], [10, 2]];
|
||||
expectedNextEditPoints.forEach(([line, col]) => {
|
||||
fetchEditPoint('next');
|
||||
testSelection(editor.selection, col, line);
|
||||
});
|
||||
|
||||
let expectedPrevEditPoints = [[6, 8], [4, 16], [4, 16]];
|
||||
const expectedPrevEditPoints = [[6, 8], [4, 16], [4, 16]];
|
||||
expectedPrevEditPoints.forEach(([line, col]) => {
|
||||
fetchEditPoint('prev');
|
||||
testSelection(editor.selection, col, line);
|
||||
|
@ -82,7 +82,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(htmlContents, '.html', (editor, _) => {
|
||||
editor.selections = [new Selection(2, 2, 2, 2)];
|
||||
|
||||
let expectedNextItemPoints: [number, number, number][] = [
|
||||
const expectedNextItemPoints: [number, number, number][] = [
|
||||
[2, 1, 5], // html
|
||||
[2, 6, 15], // lang="en"
|
||||
[2, 12, 14], // en
|
||||
|
@ -141,7 +141,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(templateContents, '.html', (editor, _) => {
|
||||
editor.selections = [new Selection(2, 2, 2, 2)];
|
||||
|
||||
let expectedNextItemPoints: [number, number, number][] = [
|
||||
const expectedNextItemPoints: [number, number, number][] = [
|
||||
[2, 2, 5], // div
|
||||
[2, 6, 20], // class="header"
|
||||
[2, 13, 19], // header
|
||||
|
@ -170,7 +170,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(cssContents, '.css', (editor, _) => {
|
||||
editor.selections = [new Selection(0, 0, 0, 0)];
|
||||
|
||||
let expectedNextItemPoints: [number, number, number][] = [
|
||||
const expectedNextItemPoints: [number, number, number][] = [
|
||||
[1, 0, 4], // .boo
|
||||
[2, 1, 19], // margin: 20px 10px;
|
||||
[2, 9, 18], // 20px 10px
|
||||
|
@ -201,7 +201,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(scssContents, '.scss', (editor, _) => {
|
||||
editor.selections = [new Selection(0, 0, 0, 0)];
|
||||
|
||||
let expectedNextItemPoints: [number, number, number][] = [
|
||||
const expectedNextItemPoints: [number, number, number][] = [
|
||||
[1, 0, 4], // .boo
|
||||
[2, 1, 19], // margin: 20px 10px;
|
||||
[2, 9, 18], // 20px 10px
|
||||
|
@ -232,7 +232,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(htmlContents, 'html', (editor, _) => {
|
||||
|
||||
editor.selections = [new Selection(14, 6, 14, 10)];
|
||||
let expectedBalanceOutRanges: [number, number, number, number][] = [
|
||||
const expectedBalanceOutRanges: [number, number, number, number][] = [
|
||||
[14, 3, 14, 32], // <li class="item1">Item 1</li>
|
||||
[13, 23, 16, 2], // inner contents of <ul class="nav main">
|
||||
[13, 2, 16, 7], // outer contents of <ul class="nav main">
|
||||
|
@ -249,7 +249,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
});
|
||||
|
||||
editor.selections = [new Selection(12, 7, 12, 7)];
|
||||
let expectedBalanceInRanges: [number, number, number, number][] = [
|
||||
const expectedBalanceInRanges: [number, number, number, number][] = [
|
||||
[12, 21, 17, 1], // inner contents of <div class="header">
|
||||
[13, 2, 16, 7], // outer contents of <ul class="nav main">
|
||||
[13, 23, 16, 2], // inner contents of <ul class="nav main">
|
||||
|
@ -269,7 +269,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(htmlContents, 'html', (editor, _) => {
|
||||
|
||||
editor.selections = [new Selection(15, 6, 15, 10)];
|
||||
let expectedBalanceOutRanges: [number, number, number, number][] = [
|
||||
const expectedBalanceOutRanges: [number, number, number, number][] = [
|
||||
[15, 3, 15, 32], // <li class="item1">Item 2</li>
|
||||
[13, 23, 16, 2], // inner contents of <ul class="nav main">
|
||||
[13, 2, 16, 7], // outer contents of <ul class="nav main">
|
||||
|
@ -327,7 +327,7 @@ suite('Tests for Next/Previous Select/Edit point and Balance actions', () => {
|
|||
return withRandomFileEditor(htmlTemplate, 'html', (editor, _) => {
|
||||
|
||||
editor.selections = [new Selection(5, 24, 5, 24)];
|
||||
let expectedBalanceOutRanges: [number, number, number, number][] = [
|
||||
const expectedBalanceOutRanges: [number, number, number, number][] = [
|
||||
[5, 20, 5, 26], // <li class="item1">``Item 2''</li>
|
||||
[5, 2, 5, 31], // ``<li class="item1">Item 2</li>''
|
||||
[3, 22, 6, 1], // inner contents of ul
|
||||
|
|
|
@ -30,12 +30,12 @@ p {
|
|||
} p
|
||||
`;
|
||||
return withRandomFileEditor(cssContents, '.css', (_, doc) => {
|
||||
let rangesForEmmet = [
|
||||
const rangesForEmmet = [
|
||||
new vscode.Range(3, 18, 3, 19), // Same line after block comment
|
||||
new vscode.Range(4, 1, 4, 2), // p after block comment
|
||||
new vscode.Range(5, 1, 5, 3) // p. after block comment
|
||||
];
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(1, 0, 1, 1), // Selector
|
||||
new vscode.Range(2, 9, 2, 10), // Property value
|
||||
new vscode.Range(3, 3, 3, 5), // dn inside block comment
|
||||
|
@ -65,7 +65,7 @@ dn {
|
|||
} bg
|
||||
`;
|
||||
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(1, 0, 1, 4), // Selector
|
||||
new vscode.Range(2, 3, 2, 7), // Line commented selector
|
||||
new vscode.Range(3, 3, 3, 7), // Block commented selector
|
||||
|
@ -94,12 +94,12 @@ comment */
|
|||
} p
|
||||
`;
|
||||
return withRandomFileEditor(cssContents, '.css', (_, doc) => {
|
||||
let rangesForEmmet = [
|
||||
const rangesForEmmet = [
|
||||
new vscode.Range(7, 18, 7, 19), // Same line after block comment
|
||||
new vscode.Range(8, 1, 8, 2), // p after block comment
|
||||
new vscode.Range(9, 1, 9, 3) // p. after block comment
|
||||
];
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(1, 2, 1, 3), // Selector
|
||||
new vscode.Range(3, 3, 3, 4), // Inside multiline comment
|
||||
new vscode.Range(5, 0, 5, 1), // Opening Brace
|
||||
|
@ -133,13 +133,13 @@ comment */
|
|||
}}}
|
||||
`;
|
||||
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
|
||||
let rangesForEmmet = [
|
||||
const rangesForEmmet = [
|
||||
new vscode.Range(2, 1, 2, 2), // Inside a ruleset before errors
|
||||
new vscode.Range(3, 1, 3, 2), // Inside a ruleset after no serious error
|
||||
new vscode.Range(7, 1, 7, 2), // @ inside a so far well structured ruleset
|
||||
new vscode.Range(9, 2, 9, 3), // @ inside a so far well structured nested ruleset
|
||||
];
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(4, 4, 4, 5), // p inside ruleset without proper selector
|
||||
new vscode.Range(6, 3, 6, 4) // In selector
|
||||
];
|
||||
|
@ -158,14 +158,14 @@ comment */
|
|||
.foo{dn}.bar{.boo{dn}dn}.comd{/*{dn*/p{div{dn}} }.foo{.other{dn}} dn
|
||||
`;
|
||||
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
|
||||
let rangesForEmmet = [
|
||||
const rangesForEmmet = [
|
||||
new vscode.Range(1, 5, 1, 7), // Inside a ruleset
|
||||
new vscode.Range(1, 18, 1, 20), // Inside a nested ruleset
|
||||
new vscode.Range(1, 21, 1, 23), // Inside ruleset after nested one.
|
||||
new vscode.Range(1, 43, 1, 45), // Inside nested ruleset after comment
|
||||
new vscode.Range(1, 61, 1, 63) // Inside nested ruleset
|
||||
];
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(1, 3, 1, 4), // In foo selector
|
||||
new vscode.Range(1, 10, 1, 11), // In bar selector
|
||||
new vscode.Range(1, 15, 1, 16), // In boo selector
|
||||
|
@ -197,11 +197,11 @@ p.#{dn} {
|
|||
}
|
||||
`;
|
||||
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
|
||||
let rangesForEmmet = [
|
||||
const rangesForEmmet = [
|
||||
new vscode.Range(2, 1, 2, 4), // p.3 inside a ruleset whose selector uses interpolation
|
||||
new vscode.Range(4, 1, 4, 3) // dn inside ruleset after property with variable
|
||||
];
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(1, 0, 1, 1), // In p in selector
|
||||
new vscode.Range(1, 2, 1, 3), // In # in selector
|
||||
new vscode.Range(1, 4, 1, 6), // In dn inside variable in selector
|
||||
|
@ -237,13 +237,13 @@ ment */{
|
|||
}
|
||||
`;
|
||||
return withRandomFileEditor(sassContents, '.scss', (_, doc) => {
|
||||
let rangesForEmmet = [
|
||||
const rangesForEmmet = [
|
||||
new vscode.Range(2, 14, 2, 21), // brs6-2p with a block commented line comment ('/* */' overrides '//')
|
||||
new vscode.Range(3, 1, 3, 3), // dn after a line with combined comments inside a ruleset
|
||||
new vscode.Range(9, 1, 9, 4), // m10 inside ruleset whose selector is before a comment
|
||||
new vscode.Range(12, 1, 12, 5) // op3 inside a ruleset with commented extra braces
|
||||
];
|
||||
let rangesNotEmmet = [
|
||||
const rangesNotEmmet = [
|
||||
new vscode.Range(2, 4, 2, 5), // In p inside block comment
|
||||
new vscode.Range(2, 9, 2, 10), // In p inside block comment and after line comment
|
||||
new vscode.Range(6, 3, 6, 4) // In c inside block comment
|
||||
|
|
|
@ -43,7 +43,7 @@ suite('Tests for Emmet actions on html tags', () => {
|
|||
</div>
|
||||
`;
|
||||
|
||||
let contentsWithTemplate = `
|
||||
const contentsWithTemplate = `
|
||||
<script type="text/template">
|
||||
<ul>
|
||||
<li><span>Hello</span></li>
|
||||
|
@ -353,7 +353,7 @@ suite('Tests for Emmet actions on html tags', () => {
|
|||
});
|
||||
|
||||
test('match tag with template scripts', () => {
|
||||
let templateScript = `
|
||||
const templateScript = `
|
||||
<script type="text/template">
|
||||
<div>
|
||||
Hello
|
||||
|
|
|
@ -27,7 +27,7 @@ export function toggleComment(): Thenable<boolean> | undefined {
|
|||
}
|
||||
|
||||
return editor.edit(editBuilder => {
|
||||
let allEdits: vscode.TextEdit[][] = [];
|
||||
const allEdits: vscode.TextEdit[][] = [];
|
||||
Array.from(editor.selections).reverse().forEach(selection => {
|
||||
const edits = isStyleSheet(editor.document.languageId) ? toggleCommentStylesheet(editor.document, selection, <Stylesheet>rootNode) : toggleCommentHTML(editor.document, selection, rootNode!);
|
||||
if (edits.length > 0) {
|
||||
|
@ -37,7 +37,7 @@ export function toggleComment(): Thenable<boolean> | undefined {
|
|||
|
||||
// Apply edits in order so we can skip nested ones.
|
||||
allEdits.sort((arr1, arr2) => {
|
||||
let result = arr1[0].range.start.line - arr2[0].range.start.line;
|
||||
const result = arr1[0].range.start.line - arr2[0].range.start.line;
|
||||
return result === 0 ? arr1[0].range.start.character - arr2[0].range.start.character : result;
|
||||
});
|
||||
let lastEditPosition = new vscode.Position(0, 0);
|
||||
|
@ -76,7 +76,7 @@ function toggleCommentHTML(document: vscode.TextDocument, selection: vscode.Sele
|
|||
return toggleCommentStylesheet(document, selection, cssRootNode);
|
||||
}
|
||||
|
||||
let allNodes: Node[] = getNodesInBetween(startNode, endNode);
|
||||
const allNodes: Node[] = getNodesInBetween(startNode, endNode);
|
||||
let edits: vscode.TextEdit[] = [];
|
||||
|
||||
allNodes.forEach(node => {
|
||||
|
@ -132,8 +132,8 @@ function toggleCommentStylesheet(document: vscode.TextDocument, selection: vscod
|
|||
}
|
||||
|
||||
// Uncomment the comments that intersect with the selection.
|
||||
let rangesToUnComment: vscode.Range[] = [];
|
||||
let edits: vscode.TextEdit[] = [];
|
||||
const rangesToUnComment: vscode.Range[] = [];
|
||||
const edits: vscode.TextEdit[] = [];
|
||||
rootNode.comments.forEach(comment => {
|
||||
const commentRange = offsetRangeToVsRange(document, comment.start, comment.end);
|
||||
if (selection.intersection(commentRange)) {
|
||||
|
|
|
@ -193,7 +193,7 @@ function updateHTMLTag(editor: TextEditor, node: HtmlNode, width: number, height
|
|||
const quote = getAttributeQuote(editor, srcAttr);
|
||||
const endOfAttributes = node.attributes[node.attributes.length - 1].end;
|
||||
|
||||
let edits: TextEdit[] = [];
|
||||
const edits: TextEdit[] = [];
|
||||
let textToAdd = '';
|
||||
|
||||
if (!widthAttr) {
|
||||
|
@ -226,7 +226,7 @@ function updateCSSNode(editor: TextEditor, srcProp: Property, width: number, hei
|
|||
const separator = srcProp.separator || ': ';
|
||||
const before = getPropertyDelimitor(editor, srcProp);
|
||||
|
||||
let edits: TextEdit[] = [];
|
||||
const edits: TextEdit[] = [];
|
||||
if (!srcProp.terminatorToken) {
|
||||
edits.push(new TextEdit(offsetRangeToVsRange(document, srcProp.end, srcProp.end), ';'));
|
||||
}
|
||||
|
|
|
@ -54,7 +54,7 @@ export async function updateTag(tagName: string | undefined): Promise<boolean |
|
|||
}
|
||||
|
||||
function getRangesFromNode(node: HtmlFlatNode, document: vscode.TextDocument): TagRange[] {
|
||||
let ranges: TagRange[] = [];
|
||||
const ranges: TagRange[] = [];
|
||||
if (node.open) {
|
||||
const start = document.positionAt(node.open.start);
|
||||
ranges.push({
|
||||
|
|
|
@ -58,7 +58,7 @@ export function updateEmmetExtensionsPath(forceRefresh: boolean = false) {
|
|||
*/
|
||||
export function migrateEmmetExtensionsPath() {
|
||||
// Get the detail info of emmet.extensionsPath setting
|
||||
let config = vscode.workspace.getConfiguration().inspect('emmet.extensionsPath');
|
||||
const config = vscode.workspace.getConfiguration().inspect('emmet.extensionsPath');
|
||||
|
||||
// Update Global setting if the value type is string or the value is null
|
||||
if (typeof config?.globalValue === 'string') {
|
||||
|
@ -100,12 +100,12 @@ export const LANGUAGE_MODES: { [id: string]: string[] } = {
|
|||
};
|
||||
|
||||
export function isStyleSheet(syntax: string): boolean {
|
||||
let stylesheetSyntaxes = ['css', 'scss', 'sass', 'less', 'stylus'];
|
||||
const stylesheetSyntaxes = ['css', 'scss', 'sass', 'less', 'stylus'];
|
||||
return stylesheetSyntaxes.includes(syntax);
|
||||
}
|
||||
|
||||
export function validate(allowStylesheet: boolean = true): boolean {
|
||||
let editor = vscode.window.activeTextEditor;
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) {
|
||||
vscode.window.showInformationMessage('No editor is active');
|
||||
return false;
|
||||
|
@ -197,7 +197,7 @@ export function parsePartialStylesheet(document: vscode.TextDocument, position:
|
|||
|
||||
function findOpeningCommentBeforePosition(pos: number): number | undefined {
|
||||
const text = document.getText().substring(0, pos);
|
||||
let offset = text.lastIndexOf('/*');
|
||||
const offset = text.lastIndexOf('/*');
|
||||
if (offset === -1) {
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -338,7 +338,7 @@ export class ExtensionLinter {
|
|||
|
||||
if (!hasScheme && !info.hasHttpsRepository) {
|
||||
const range = new Range(document.positionAt(begin), document.positionAt(end));
|
||||
let message = (() => {
|
||||
const message = (() => {
|
||||
switch (context) {
|
||||
case Context.ICON: return relativeIconUrlRequiresHttpsRepository;
|
||||
case Context.BADGE: return relativeBadgeUrlRequiresHttpsRepository;
|
||||
|
@ -367,7 +367,7 @@ export class ExtensionLinter {
|
|||
|
||||
function parseUri(src: string, base?: string, retry: boolean = true): Uri | null {
|
||||
try {
|
||||
let url = new URL(src, base);
|
||||
const url = new URL(src, base);
|
||||
return Uri.parse(url.toString());
|
||||
} catch (err) {
|
||||
if (retry) {
|
||||
|
|
|
@ -80,7 +80,7 @@ export class Askpass implements IIPCHandler {
|
|||
};
|
||||
}
|
||||
|
||||
let env: { [key: string]: string } = {
|
||||
const env: { [key: string]: string } = {
|
||||
...this.ipc.getEnv(),
|
||||
VSCODE_GIT_ASKPASS_NODE: process.execPath,
|
||||
VSCODE_GIT_ASKPASS_EXTRA_ARGS: (process.versions['electron'] && process.versions['microsoft-build']) ? '--ms-enable-electron-run-as-node' : '',
|
||||
|
|
|
@ -418,8 +418,8 @@ export class CommandCenter {
|
|||
|
||||
type InputData = { uri: Uri; detail?: string; description?: string };
|
||||
const mergeUris = toMergeUris(uri);
|
||||
let input1: InputData = { uri: mergeUris.ours };
|
||||
let input2: InputData = { uri: mergeUris.theirs };
|
||||
const input1: InputData = { uri: mergeUris.ours };
|
||||
const input2: InputData = { uri: mergeUris.theirs };
|
||||
|
||||
try {
|
||||
const [head, mergeHead] = await Promise.all([repo.getCommit('HEAD'), repo.getCommit('MERGE_HEAD')]);
|
||||
|
@ -1561,7 +1561,7 @@ export class CommandCenter {
|
|||
}
|
||||
}
|
||||
|
||||
let message = await getCommitMessage();
|
||||
const message = await getCommitMessage();
|
||||
|
||||
if (!message && !opts.amend) {
|
||||
return false;
|
||||
|
@ -1627,7 +1627,7 @@ export class CommandCenter {
|
|||
let _message: string | undefined = message;
|
||||
|
||||
if (!_message) {
|
||||
let value: string | undefined = undefined;
|
||||
const value: string | undefined = undefined;
|
||||
|
||||
if (opts && opts.amend && repository.HEAD && repository.HEAD.commit) {
|
||||
return undefined;
|
||||
|
|
|
@ -106,7 +106,7 @@ class GitDecorationProvider implements FileDecorationProvider {
|
|||
}
|
||||
|
||||
private onDidRunGitStatus(): void {
|
||||
let newDecorations = new Map<string, FileDecoration>();
|
||||
const newDecorations = new Map<string, FileDecoration>();
|
||||
|
||||
this.collectSubmoduleDecorationData(newDecorations);
|
||||
this.collectDecorationData(this.repository.indexGroup, newDecorations);
|
||||
|
|
|
@ -50,7 +50,7 @@ const JSCHARDET_TO_ICONV_ENCODINGS: { [name: string]: string } = {
|
|||
};
|
||||
|
||||
export function detectEncoding(buffer: Buffer): string | null {
|
||||
let result = detectEncodingByBOM(buffer);
|
||||
const result = detectEncodingByBOM(buffer);
|
||||
|
||||
if (result) {
|
||||
return result;
|
||||
|
|
|
@ -406,7 +406,7 @@ export class Git {
|
|||
}
|
||||
|
||||
async clone(url: string, options: ICloneOptions, cancellationToken?: CancellationToken): Promise<string> {
|
||||
let baseFolderName = decodeURI(url).replace(/[\/]+$/, '').replace(/^.*[\/\\]/, '').replace(/\.git$/, '') || 'repository';
|
||||
const baseFolderName = decodeURI(url).replace(/[\/]+$/, '').replace(/^.*[\/\\]/, '').replace(/\.git$/, '') || 'repository';
|
||||
let folderName = baseFolderName;
|
||||
let folderPath = path.join(options.parentPath, folderName);
|
||||
let count = 1;
|
||||
|
@ -447,7 +447,7 @@ export class Git {
|
|||
};
|
||||
|
||||
try {
|
||||
let command = ['clone', url.includes(' ') ? encodeURI(url) : url, folderPath, '--progress'];
|
||||
const command = ['clone', url.includes(' ') ? encodeURI(url) : url, folderPath, '--progress'];
|
||||
if (options.recursive) {
|
||||
command.push('--recursive');
|
||||
}
|
||||
|
@ -481,7 +481,7 @@ export class Git {
|
|||
const pathUri = Uri.file(repositoryPath);
|
||||
if (repoUri.authority.length !== 0 && pathUri.authority.length === 0) {
|
||||
// eslint-disable-next-line code-no-look-behind-regex
|
||||
let match = /(?<=^\/?)([a-zA-Z])(?=:\/)/.exec(pathUri.path);
|
||||
const match = /(?<=^\/?)([a-zA-Z])(?=:\/)/.exec(pathUri.path);
|
||||
if (match !== null) {
|
||||
const [, letter] = match;
|
||||
|
||||
|
@ -794,7 +794,7 @@ export function parseGitmodules(raw: string): Submodule[] {
|
|||
const commitRegex = /([0-9a-f]{40})\n(.*)\n(.*)\n(.*)\n(.*)\n(.*)\n(.*)(?:\n([^]*?))?(?:\x00)/gm;
|
||||
|
||||
export function parseGitCommits(data: string): Commit[] {
|
||||
let commits: Commit[] = [];
|
||||
const commits: Commit[] = [];
|
||||
|
||||
let ref;
|
||||
let authorName;
|
||||
|
@ -1543,7 +1543,7 @@ export class Repository {
|
|||
}
|
||||
|
||||
async deleteTag(name: string): Promise<void> {
|
||||
let args = ['tag', '-d', name];
|
||||
const args = ['tag', '-d', name];
|
||||
await this.exec(args);
|
||||
}
|
||||
|
||||
|
|
|
@ -9,7 +9,7 @@ export function applyLineChanges(original: TextDocument, modified: TextDocument,
|
|||
const result: string[] = [];
|
||||
let currentLine = 0;
|
||||
|
||||
for (let diff of diffs) {
|
||||
for (const diff of diffs) {
|
||||
const isInsertion = diff.originalEndLineNumber === 0;
|
||||
const isDeletion = diff.modifiedEndLineNumber === 0;
|
||||
|
||||
|
|
|
@ -89,7 +89,7 @@ export function eventToPromise<T>(event: Event<T>): Promise<T> {
|
|||
}
|
||||
|
||||
export function once(fn: (...args: any[]) => any): (...args: any[]) => any {
|
||||
let didRun = false;
|
||||
const didRun = false;
|
||||
|
||||
return (...args) => {
|
||||
if (didRun) {
|
||||
|
@ -219,11 +219,11 @@ export async function grep(filename: string, pattern: RegExp): Promise<boolean>
|
|||
export function readBytes(stream: Readable, bytes: number): Promise<Buffer> {
|
||||
return new Promise<Buffer>((complete, error) => {
|
||||
let done = false;
|
||||
let buffer = Buffer.allocUnsafe(bytes);
|
||||
const buffer = Buffer.allocUnsafe(bytes);
|
||||
let bytesRead = 0;
|
||||
|
||||
stream.on('data', (data: Buffer) => {
|
||||
let bytesToRead = Math.min(bytes - bytesRead, data.length);
|
||||
const bytesToRead = Math.min(bytes - bytesRead, data.length);
|
||||
data.copy(buffer, bytesRead, 0, bytesToRead);
|
||||
bytesRead += bytesToRead;
|
||||
|
||||
|
|
|
@ -51,7 +51,7 @@ export function promiseFromEvent<T, U>(
|
|||
event: Event<T>,
|
||||
adapter: PromiseAdapter<T, U> = passthrough): { promise: Promise<U>; cancel: EventEmitter<void> } {
|
||||
let subscription: Disposable;
|
||||
let cancel = new EventEmitter<void>();
|
||||
const cancel = new EventEmitter<void>();
|
||||
return {
|
||||
promise: new Promise<U>((resolve, reject) => {
|
||||
cancel.event(_ => reject('Cancelled'));
|
||||
|
|
|
@ -107,7 +107,7 @@ export class GithubRemoteSourceProvider implements RemoteSourceProvider {
|
|||
let page = 1;
|
||||
|
||||
while (true) {
|
||||
let res = await octokit.repos.listBranches({ ...repository, per_page: 100, page });
|
||||
const res = await octokit.repos.listBranches({ ...repository, per_page: 100, page });
|
||||
|
||||
if (res.data.length === 0) {
|
||||
break;
|
||||
|
|
|
@ -33,7 +33,7 @@ function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: strin
|
|||
|
||||
const buildNames: string[] = ['build', 'compile', 'watch'];
|
||||
function isBuildTask(name: string): boolean {
|
||||
for (let buildName of buildNames) {
|
||||
for (const buildName of buildNames) {
|
||||
if (name.indexOf(buildName) !== -1) {
|
||||
return true;
|
||||
}
|
||||
|
@ -43,7 +43,7 @@ function isBuildTask(name: string): boolean {
|
|||
|
||||
const testNames: string[] = ['test'];
|
||||
function isTestTask(name: string): boolean {
|
||||
for (let testName of testNames) {
|
||||
for (const testName of testNames) {
|
||||
if (name.indexOf(testName) !== -1) {
|
||||
return true;
|
||||
}
|
||||
|
@ -73,7 +73,7 @@ interface GruntTaskDefinition extends vscode.TaskDefinition {
|
|||
|
||||
async function findGruntCommand(rootPath: string): Promise<string> {
|
||||
let command: string;
|
||||
let platform = process.platform;
|
||||
const platform = process.platform;
|
||||
if (platform === 'win32' && await exists(path.join(rootPath!, 'node_modules', '.bin', 'grunt.cmd'))) {
|
||||
command = path.join('.', 'node_modules', '.bin', 'grunt.cmd');
|
||||
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(rootPath!, 'node_modules', '.bin', 'grunt'))) {
|
||||
|
@ -103,7 +103,7 @@ class FolderDetector {
|
|||
}
|
||||
|
||||
public start(): void {
|
||||
let pattern = path.join(this._workspaceFolder.uri.fsPath, '{node_modules,[Gg]runtfile.js}');
|
||||
const pattern = path.join(this._workspaceFolder.uri.fsPath, '{node_modules,[Gg]runtfile.js}');
|
||||
this.fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
|
||||
this.fileWatcher.onDidChange(() => this.promise = undefined);
|
||||
this.fileWatcher.onDidCreate(() => this.promise = undefined);
|
||||
|
@ -125,9 +125,9 @@ class FolderDetector {
|
|||
const taskDefinition = <any>_task.definition;
|
||||
const gruntTask = taskDefinition.task;
|
||||
if (gruntTask) {
|
||||
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
let source = 'grunt';
|
||||
let task = gruntTask.indexOf(' ') === -1
|
||||
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
const source = 'grunt';
|
||||
const task = gruntTask.indexOf(' ') === -1
|
||||
? new vscode.Task(taskDefinition, this.workspaceFolder, gruntTask, source, new vscode.ShellExecution(`${await this._gruntCommand}`, [gruntTask, ...taskDefinition.args], options))
|
||||
: new vscode.Task(taskDefinition, this.workspaceFolder, gruntTask, source, new vscode.ShellExecution(`${await this._gruntCommand}`, [`"${gruntTask}"`, ...taskDefinition.args], options));
|
||||
return task;
|
||||
|
@ -136,8 +136,8 @@ class FolderDetector {
|
|||
}
|
||||
|
||||
private async computeTasks(): Promise<vscode.Task[]> {
|
||||
let rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
|
||||
let emptyTasks: vscode.Task[] = [];
|
||||
const rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
|
||||
const emptyTasks: vscode.Task[] = [];
|
||||
if (!rootPath) {
|
||||
return emptyTasks;
|
||||
}
|
||||
|
@ -145,14 +145,14 @@ class FolderDetector {
|
|||
return emptyTasks;
|
||||
}
|
||||
|
||||
let commandLine = `${await this._gruntCommand} --help --no-color`;
|
||||
const commandLine = `${await this._gruntCommand} --help --no-color`;
|
||||
try {
|
||||
let { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
|
||||
const { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
|
||||
if (stderr) {
|
||||
getOutputChannel().appendLine(stderr);
|
||||
showError();
|
||||
}
|
||||
let result: vscode.Task[] = [];
|
||||
const result: vscode.Task[] = [];
|
||||
if (stdout) {
|
||||
// grunt lists tasks as follows (description is wrapped into a new line if too long):
|
||||
// ...
|
||||
|
@ -166,10 +166,10 @@ class FolderDetector {
|
|||
//
|
||||
// Tasks run in the order specified
|
||||
|
||||
let lines = stdout.split(/\r{0,1}\n/);
|
||||
const lines = stdout.split(/\r{0,1}\n/);
|
||||
let tasksStart = false;
|
||||
let tasksEnd = false;
|
||||
for (let line of lines) {
|
||||
for (const line of lines) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
@ -181,21 +181,21 @@ class FolderDetector {
|
|||
if (line.indexOf('Tasks run in the order specified') === 0) {
|
||||
tasksEnd = true;
|
||||
} else {
|
||||
let regExp = /^\s*(\S.*\S) \S/g;
|
||||
let matches = regExp.exec(line);
|
||||
const regExp = /^\s*(\S.*\S) \S/g;
|
||||
const matches = regExp.exec(line);
|
||||
if (matches && matches.length === 2) {
|
||||
let name = matches[1];
|
||||
let kind: GruntTaskDefinition = {
|
||||
const name = matches[1];
|
||||
const kind: GruntTaskDefinition = {
|
||||
type: 'grunt',
|
||||
task: name
|
||||
};
|
||||
let source = 'grunt';
|
||||
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
let task = name.indexOf(' ') === -1
|
||||
const source = 'grunt';
|
||||
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
const task = name.indexOf(' ') === -1
|
||||
? new vscode.Task(kind, this.workspaceFolder, name, source, new vscode.ShellExecution(`${await this._gruntCommand} ${name}`, options))
|
||||
: new vscode.Task(kind, this.workspaceFolder, name, source, new vscode.ShellExecution(`${await this._gruntCommand} "${name}"`, options));
|
||||
result.push(task);
|
||||
let lowerCaseTaskName = name.toLowerCase();
|
||||
const lowerCaseTaskName = name.toLowerCase();
|
||||
if (isBuildTask(lowerCaseTaskName)) {
|
||||
task.group = vscode.TaskGroup.Build;
|
||||
} else if (isTestTask(lowerCaseTaskName)) {
|
||||
|
@ -208,7 +208,7 @@ class FolderDetector {
|
|||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
let channel = getOutputChannel();
|
||||
const channel = getOutputChannel();
|
||||
if (err.stderr) {
|
||||
channel.appendLine(err.stderr);
|
||||
}
|
||||
|
@ -238,7 +238,7 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
public start(): void {
|
||||
let folders = vscode.workspace.workspaceFolders;
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (folders) {
|
||||
this.updateWorkspaceFolders(folders, []);
|
||||
}
|
||||
|
@ -255,15 +255,15 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
private updateWorkspaceFolders(added: readonly vscode.WorkspaceFolder[], removed: readonly vscode.WorkspaceFolder[]): void {
|
||||
for (let remove of removed) {
|
||||
let detector = this.detectors.get(remove.uri.toString());
|
||||
for (const remove of removed) {
|
||||
const detector = this.detectors.get(remove.uri.toString());
|
||||
if (detector) {
|
||||
detector.dispose();
|
||||
this.detectors.delete(remove.uri.toString());
|
||||
}
|
||||
}
|
||||
for (let add of added) {
|
||||
let detector = new FolderDetector(add, findGruntCommand(add.uri.fsPath));
|
||||
for (const add of added) {
|
||||
const detector = new FolderDetector(add, findGruntCommand(add.uri.fsPath));
|
||||
this.detectors.set(add.uri.toString(), detector);
|
||||
if (detector.isEnabled()) {
|
||||
detector.start();
|
||||
|
@ -273,15 +273,15 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
private updateConfiguration(): void {
|
||||
for (let detector of this.detectors.values()) {
|
||||
for (const detector of this.detectors.values()) {
|
||||
detector.dispose();
|
||||
this.detectors.delete(detector.workspaceFolder.uri.toString());
|
||||
}
|
||||
let folders = vscode.workspace.workspaceFolders;
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (folders) {
|
||||
for (let folder of folders) {
|
||||
for (const folder of folders) {
|
||||
if (!this.detectors.has(folder.uri.toString())) {
|
||||
let detector = new FolderDetector(folder, findGruntCommand(folder.uri.fsPath));
|
||||
const detector = new FolderDetector(folder, findGruntCommand(folder.uri.fsPath));
|
||||
this.detectors.set(folder.uri.toString(), detector);
|
||||
if (detector.isEnabled()) {
|
||||
detector.start();
|
||||
|
@ -320,13 +320,13 @@ class TaskDetector {
|
|||
} else if (this.detectors.size === 1) {
|
||||
return this.detectors.values().next().value.getTasks();
|
||||
} else {
|
||||
let promises: Promise<vscode.Task[]>[] = [];
|
||||
for (let detector of this.detectors.values()) {
|
||||
const promises: Promise<vscode.Task[]>[] = [];
|
||||
for (const detector of this.detectors.values()) {
|
||||
promises.push(detector.getTasks().then((value) => value, () => []));
|
||||
}
|
||||
return Promise.all(promises).then((values) => {
|
||||
let result: vscode.Task[] = [];
|
||||
for (let tasks of values) {
|
||||
const result: vscode.Task[] = [];
|
||||
for (const tasks of values) {
|
||||
if (tasks && tasks.length > 0) {
|
||||
result.push(...tasks);
|
||||
}
|
||||
|
|
|
@ -53,7 +53,7 @@ function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: strin
|
|||
|
||||
const buildNames: string[] = ['build', 'compile', 'watch'];
|
||||
function isBuildTask(name: string): boolean {
|
||||
for (let buildName of buildNames) {
|
||||
for (const buildName of buildNames) {
|
||||
if (name.indexOf(buildName) !== -1) {
|
||||
return true;
|
||||
}
|
||||
|
@ -63,7 +63,7 @@ function isBuildTask(name: string): boolean {
|
|||
|
||||
const testNames: string[] = ['test'];
|
||||
function isTestTask(name: string): boolean {
|
||||
for (let testName of testNames) {
|
||||
for (const testName of testNames) {
|
||||
if (name.indexOf(testName) !== -1) {
|
||||
return true;
|
||||
}
|
||||
|
@ -89,7 +89,7 @@ function showError() {
|
|||
}
|
||||
|
||||
async function findGulpCommand(rootPath: string): Promise<string> {
|
||||
let platform = process.platform;
|
||||
const platform = process.platform;
|
||||
|
||||
if (platform === 'win32' && await exists(path.join(rootPath, 'node_modules', '.bin', 'gulp.cmd'))) {
|
||||
const globalGulp = path.join(process.env.APPDATA ? process.env.APPDATA : '', 'npm', 'gulp.cmd');
|
||||
|
@ -132,7 +132,7 @@ class FolderDetector {
|
|||
}
|
||||
|
||||
public start(): void {
|
||||
let pattern = path.join(this._workspaceFolder.uri.fsPath, '{node_modules,gulpfile{.babel.js,.esm.js,.js,.mjs,.cjs,.ts}}');
|
||||
const pattern = path.join(this._workspaceFolder.uri.fsPath, '{node_modules,gulpfile{.babel.js,.esm.js,.js,.mjs,.cjs,.ts}}');
|
||||
this.fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
|
||||
this.fileWatcher.onDidChange(() => this.promise = undefined);
|
||||
this.fileWatcher.onDidCreate(() => this.promise = undefined);
|
||||
|
@ -154,9 +154,9 @@ class FolderDetector {
|
|||
public async getTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
|
||||
const gulpTask = (<any>_task.definition).task;
|
||||
if (gulpTask) {
|
||||
let kind: GulpTaskDefinition = (<any>_task.definition);
|
||||
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
let task = new vscode.Task(kind, this.workspaceFolder, gulpTask, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [gulpTask], options));
|
||||
const kind: GulpTaskDefinition = (<any>_task.definition);
|
||||
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
const task = new vscode.Task(kind, this.workspaceFolder, gulpTask, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [gulpTask], options));
|
||||
return task;
|
||||
}
|
||||
return undefined;
|
||||
|
@ -187,7 +187,7 @@ class FolderDetector {
|
|||
continue;
|
||||
}
|
||||
|
||||
let basename = path.basename(filename, ext).toLowerCase();
|
||||
const basename = path.basename(filename, ext).toLowerCase();
|
||||
if (basename === 'gulpfile') {
|
||||
return true;
|
||||
}
|
||||
|
@ -203,8 +203,8 @@ class FolderDetector {
|
|||
}
|
||||
|
||||
private async computeTasks(): Promise<vscode.Task[]> {
|
||||
let rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
|
||||
let emptyTasks: vscode.Task[] = [];
|
||||
const rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
|
||||
const emptyTasks: vscode.Task[] = [];
|
||||
if (!rootPath) {
|
||||
return emptyTasks;
|
||||
}
|
||||
|
@ -213,9 +213,9 @@ class FolderDetector {
|
|||
return emptyTasks;
|
||||
}
|
||||
|
||||
let commandLine = `${await this._gulpCommand} --tasks-simple --no-color`;
|
||||
const commandLine = `${await this._gulpCommand} --tasks-simple --no-color`;
|
||||
try {
|
||||
let { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
|
||||
const { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
|
||||
if (stderr && stderr.length > 0) {
|
||||
// Filter out "No license field"
|
||||
const errors = stderr.split('\n');
|
||||
|
@ -225,21 +225,21 @@ class FolderDetector {
|
|||
showError();
|
||||
}
|
||||
}
|
||||
let result: vscode.Task[] = [];
|
||||
const result: vscode.Task[] = [];
|
||||
if (stdout) {
|
||||
let lines = stdout.split(/\r{0,1}\n/);
|
||||
for (let line of lines) {
|
||||
const lines = stdout.split(/\r{0,1}\n/);
|
||||
for (const line of lines) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
let kind: GulpTaskDefinition = {
|
||||
const kind: GulpTaskDefinition = {
|
||||
type: 'gulp',
|
||||
task: line
|
||||
};
|
||||
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
let task = new vscode.Task(kind, this.workspaceFolder, line, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [line], options));
|
||||
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
const task = new vscode.Task(kind, this.workspaceFolder, line, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [line], options));
|
||||
result.push(task);
|
||||
let lowerCaseLine = line.toLowerCase();
|
||||
const lowerCaseLine = line.toLowerCase();
|
||||
if (isBuildTask(lowerCaseLine)) {
|
||||
task.group = vscode.TaskGroup.Build;
|
||||
} else if (isTestTask(lowerCaseLine)) {
|
||||
|
@ -249,7 +249,7 @@ class FolderDetector {
|
|||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
let channel = getOutputChannel();
|
||||
const channel = getOutputChannel();
|
||||
if (err.stderr) {
|
||||
channel.appendLine(err.stderr);
|
||||
}
|
||||
|
@ -279,7 +279,7 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
public start(): void {
|
||||
let folders = vscode.workspace.workspaceFolders;
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (folders) {
|
||||
this.updateWorkspaceFolders(folders, []);
|
||||
}
|
||||
|
@ -296,15 +296,15 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
private updateWorkspaceFolders(added: readonly vscode.WorkspaceFolder[], removed: readonly vscode.WorkspaceFolder[]): void {
|
||||
for (let remove of removed) {
|
||||
let detector = this.detectors.get(remove.uri.toString());
|
||||
for (const remove of removed) {
|
||||
const detector = this.detectors.get(remove.uri.toString());
|
||||
if (detector) {
|
||||
detector.dispose();
|
||||
this.detectors.delete(remove.uri.toString());
|
||||
}
|
||||
}
|
||||
for (let add of added) {
|
||||
let detector = new FolderDetector(add, findGulpCommand(add.uri.fsPath));
|
||||
for (const add of added) {
|
||||
const detector = new FolderDetector(add, findGulpCommand(add.uri.fsPath));
|
||||
this.detectors.set(add.uri.toString(), detector);
|
||||
if (detector.isEnabled()) {
|
||||
detector.start();
|
||||
|
@ -314,15 +314,15 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
private updateConfiguration(): void {
|
||||
for (let detector of this.detectors.values()) {
|
||||
for (const detector of this.detectors.values()) {
|
||||
detector.dispose();
|
||||
this.detectors.delete(detector.workspaceFolder.uri.toString());
|
||||
}
|
||||
let folders = vscode.workspace.workspaceFolders;
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (folders) {
|
||||
for (let folder of folders) {
|
||||
for (const folder of folders) {
|
||||
if (!this.detectors.has(folder.uri.toString())) {
|
||||
let detector = new FolderDetector(folder, findGulpCommand(folder.uri.fsPath));
|
||||
const detector = new FolderDetector(folder, findGulpCommand(folder.uri.fsPath));
|
||||
this.detectors.set(folder.uri.toString(), detector);
|
||||
if (detector.isEnabled()) {
|
||||
detector.start();
|
||||
|
@ -361,13 +361,13 @@ class TaskDetector {
|
|||
} else if (this.detectors.size === 1) {
|
||||
return this.detectors.values().next().value.getTasks();
|
||||
} else {
|
||||
let promises: Promise<vscode.Task[]>[] = [];
|
||||
for (let detector of this.detectors.values()) {
|
||||
const promises: Promise<vscode.Task[]>[] = [];
|
||||
for (const detector of this.detectors.values()) {
|
||||
promises.push(detector.getTasks().then((value) => value, () => []));
|
||||
}
|
||||
return Promise.all(promises).then((values) => {
|
||||
let result: vscode.Task[] = [];
|
||||
for (let tasks of values) {
|
||||
const result: vscode.Task[] = [];
|
||||
for (const tasks of values) {
|
||||
if (tasks && tasks.length > 0) {
|
||||
result.push(...tasks);
|
||||
}
|
||||
|
|
|
@ -131,7 +131,7 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
};
|
||||
|
||||
// Create the language client and start the client.
|
||||
let client = newLanguageClient('html', localize('htmlserver.name', 'HTML Language Server'), clientOptions);
|
||||
const client = newLanguageClient('html', localize('htmlserver.name', 'HTML Language Server'), clientOptions);
|
||||
client.registerProposedFeatures();
|
||||
|
||||
await client.start();
|
||||
|
@ -208,7 +208,7 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
trimFinalNewlines: filesConfig.get<boolean>('trimFinalNewlines'),
|
||||
insertFinalNewline: filesConfig.get<boolean>('insertFinalNewline'),
|
||||
};
|
||||
let params: DocumentRangeFormattingParams = {
|
||||
const params: DocumentRangeFormattingParams = {
|
||||
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
|
||||
range: client.code2ProtocolConverter.asRange(range),
|
||||
options: client.code2ProtocolConverter.asFormattingOptions(options, fileFormattingOptions)
|
||||
|
@ -230,18 +230,18 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
toDispose.push(languages.registerCompletionItemProvider(documentSelector, {
|
||||
provideCompletionItems(doc, pos) {
|
||||
const results: CompletionItem[] = [];
|
||||
let lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos));
|
||||
let match = lineUntilPos.match(regionCompletionRegExpr);
|
||||
const lineUntilPos = doc.getText(new Range(new Position(pos.line, 0), pos));
|
||||
const match = lineUntilPos.match(regionCompletionRegExpr);
|
||||
if (match) {
|
||||
let range = new Range(new Position(pos.line, match[1].length), pos);
|
||||
let beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet);
|
||||
const range = new Range(new Position(pos.line, match[1].length), pos);
|
||||
const beginProposal = new CompletionItem('#region', CompletionItemKind.Snippet);
|
||||
beginProposal.range = range;
|
||||
beginProposal.insertText = new SnippetString('<!-- #region $1-->');
|
||||
beginProposal.documentation = localize('folding.start', 'Folding Region Start');
|
||||
beginProposal.filterText = match[2];
|
||||
beginProposal.sortText = 'za';
|
||||
results.push(beginProposal);
|
||||
let endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet);
|
||||
const endProposal = new CompletionItem('#endregion', CompletionItemKind.Snippet);
|
||||
endProposal.range = range;
|
||||
endProposal.insertText = new SnippetString('<!-- #endregion -->');
|
||||
endProposal.documentation = localize('folding.end', 'Folding Region End');
|
||||
|
@ -249,10 +249,10 @@ export async function startClient(context: ExtensionContext, newLanguageClient:
|
|||
endProposal.sortText = 'zb';
|
||||
results.push(endProposal);
|
||||
}
|
||||
let match2 = lineUntilPos.match(htmlSnippetCompletionRegExpr);
|
||||
const match2 = lineUntilPos.match(htmlSnippetCompletionRegExpr);
|
||||
if (match2 && doc.getText(new Range(new Position(0, 0), pos)).match(htmlSnippetCompletionRegExpr)) {
|
||||
let range = new Range(new Position(pos.line, match2[1].length), pos);
|
||||
let snippetProposal = new CompletionItem('HTML sample', CompletionItemKind.Snippet);
|
||||
const range = new Range(new Position(pos.line, match2[1].length), pos);
|
||||
const snippetProposal = new CompletionItem('HTML sample', CompletionItemKind.Snippet);
|
||||
snippetProposal.range = range;
|
||||
const content = ['<!DOCTYPE html>',
|
||||
'<html>',
|
||||
|
|
|
@ -18,7 +18,7 @@ let client: BaseLanguageClient | undefined;
|
|||
// this method is called when vs code is activated
|
||||
export async function activate(context: ExtensionContext) {
|
||||
|
||||
let clientPackageJSON = getPackageInfo(context);
|
||||
const clientPackageJSON = getPackageInfo(context);
|
||||
telemetry = new TelemetryReporter(clientPackageJSON.name, clientPackageJSON.version, clientPackageJSON.aiKey);
|
||||
|
||||
const serverMain = `./server/${clientPackageJSON.main.indexOf('/dist/') !== -1 ? 'dist' : 'out'}/node/htmlServerMain`;
|
||||
|
|
|
@ -9,56 +9,56 @@ import { LanguageMode, Workspace, Color, TextDocument, Position, Range, Completi
|
|||
import { HTMLDocumentRegions, CSS_STYLE_RULE } from './embeddedSupport';
|
||||
|
||||
export function getCSSMode(cssLanguageService: CSSLanguageService, documentRegions: LanguageModelCache<HTMLDocumentRegions>, workspace: Workspace): LanguageMode {
|
||||
let embeddedCSSDocuments = getLanguageModelCache<TextDocument>(10, 60, document => documentRegions.get(document).getEmbeddedDocument('css'));
|
||||
let cssStylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => cssLanguageService.parseStylesheet(document));
|
||||
const embeddedCSSDocuments = getLanguageModelCache<TextDocument>(10, 60, document => documentRegions.get(document).getEmbeddedDocument('css'));
|
||||
const cssStylesheets = getLanguageModelCache<Stylesheet>(10, 60, document => cssLanguageService.parseStylesheet(document));
|
||||
|
||||
return {
|
||||
getId() {
|
||||
return 'css';
|
||||
},
|
||||
async doValidation(document: TextDocument, settings = workspace.settings) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return (cssLanguageService.doValidation(embedded, cssStylesheets.get(embedded), settings && settings.css) as Diagnostic[]);
|
||||
},
|
||||
async doComplete(document: TextDocument, position: Position, documentContext: DocumentContext, _settings = workspace.settings) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
const stylesheet = cssStylesheets.get(embedded);
|
||||
return cssLanguageService.doComplete2(embedded, position, stylesheet, documentContext, _settings?.css?.completion) || CompletionList.create();
|
||||
},
|
||||
async doHover(document: TextDocument, position: Position, settings = workspace.settings) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.doHover(embedded, position, cssStylesheets.get(embedded), settings?.css?.hover);
|
||||
},
|
||||
async findDocumentHighlight(document: TextDocument, position: Position) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.findDocumentHighlights(embedded, position, cssStylesheets.get(embedded));
|
||||
},
|
||||
async findDocumentSymbols(document: TextDocument) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.findDocumentSymbols(embedded, cssStylesheets.get(embedded)).filter(s => s.name !== CSS_STYLE_RULE);
|
||||
},
|
||||
async findDefinition(document: TextDocument, position: Position) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.findDefinition(embedded, position, cssStylesheets.get(embedded));
|
||||
},
|
||||
async findReferences(document: TextDocument, position: Position) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.findReferences(embedded, position, cssStylesheets.get(embedded));
|
||||
},
|
||||
async findDocumentColors(document: TextDocument) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.findDocumentColors(embedded, cssStylesheets.get(embedded));
|
||||
},
|
||||
async getColorPresentations(document: TextDocument, color: Color, range: Range) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.getColorPresentations(embedded, cssStylesheets.get(embedded), color, range);
|
||||
},
|
||||
async getFoldingRanges(document: TextDocument) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.getFoldingRanges(embedded, {});
|
||||
},
|
||||
async getSelectionRange(document: TextDocument, position: Position) {
|
||||
let embedded = embeddedCSSDocuments.get(document);
|
||||
const embedded = embeddedCSSDocuments.get(document);
|
||||
return cssLanguageService.getSelectionRanges(embedded, [position], cssStylesheets.get(embedded))[0];
|
||||
},
|
||||
onDocumentRemoved(document: TextDocument) {
|
||||
|
|
|
@ -24,12 +24,12 @@ interface EmbeddedRegion { languageId: string | undefined; start: number; end: n
|
|||
|
||||
|
||||
export function getDocumentRegions(languageService: LanguageService, document: TextDocument): HTMLDocumentRegions {
|
||||
let regions: EmbeddedRegion[] = [];
|
||||
let scanner = languageService.createScanner(document.getText());
|
||||
const regions: EmbeddedRegion[] = [];
|
||||
const scanner = languageService.createScanner(document.getText());
|
||||
let lastTagName: string = '';
|
||||
let lastAttributeName: string | null = null;
|
||||
let languageIdFromType: string | undefined = undefined;
|
||||
let importedScripts: string[] = [];
|
||||
const importedScripts: string[] = [];
|
||||
|
||||
let token = scanner.scan();
|
||||
while (token !== TokenType.EOS) {
|
||||
|
@ -64,11 +64,11 @@ export function getDocumentRegions(languageService: LanguageService, document: T
|
|||
languageIdFromType = undefined;
|
||||
}
|
||||
} else {
|
||||
let attributeLanguageId = getAttributeLanguage(lastAttributeName!);
|
||||
const attributeLanguageId = getAttributeLanguage(lastAttributeName!);
|
||||
if (attributeLanguageId) {
|
||||
let start = scanner.getTokenOffset();
|
||||
let end = scanner.getTokenEnd();
|
||||
let firstChar = document.getText()[start];
|
||||
const firstChar = document.getText()[start];
|
||||
if (firstChar === '\'' || firstChar === '"') {
|
||||
start++;
|
||||
end--;
|
||||
|
@ -92,14 +92,14 @@ export function getDocumentRegions(languageService: LanguageService, document: T
|
|||
|
||||
|
||||
function getLanguageRanges(document: TextDocument, regions: EmbeddedRegion[], range: Range): LanguageRange[] {
|
||||
let result: LanguageRange[] = [];
|
||||
const result: LanguageRange[] = [];
|
||||
let currentPos = range ? range.start : Position.create(0, 0);
|
||||
let currentOffset = range ? document.offsetAt(range.start) : 0;
|
||||
let endOffset = range ? document.offsetAt(range.end) : document.getText().length;
|
||||
for (let region of regions) {
|
||||
const endOffset = range ? document.offsetAt(range.end) : document.getText().length;
|
||||
for (const region of regions) {
|
||||
if (region.end > currentOffset && region.start < endOffset) {
|
||||
let start = Math.max(region.start, currentOffset);
|
||||
let startPos = document.positionAt(start);
|
||||
const start = Math.max(region.start, currentOffset);
|
||||
const startPos = document.positionAt(start);
|
||||
if (currentOffset < region.start) {
|
||||
result.push({
|
||||
start: currentPos,
|
||||
|
@ -107,8 +107,8 @@ function getLanguageRanges(document: TextDocument, regions: EmbeddedRegion[], ra
|
|||
languageId: 'html'
|
||||
});
|
||||
}
|
||||
let end = Math.min(region.end, endOffset);
|
||||
let endPos = document.positionAt(end);
|
||||
const end = Math.min(region.end, endOffset);
|
||||
const endPos = document.positionAt(end);
|
||||
if (end > region.start) {
|
||||
result.push({
|
||||
start: startPos,
|
||||
|
@ -122,7 +122,7 @@ function getLanguageRanges(document: TextDocument, regions: EmbeddedRegion[], ra
|
|||
}
|
||||
}
|
||||
if (currentOffset < endOffset) {
|
||||
let endPos = range ? range.end : document.positionAt(endOffset);
|
||||
const endPos = range ? range.end : document.positionAt(endOffset);
|
||||
result.push({
|
||||
start: currentPos,
|
||||
end: endPos,
|
||||
|
@ -133,8 +133,8 @@ function getLanguageRanges(document: TextDocument, regions: EmbeddedRegion[], ra
|
|||
}
|
||||
|
||||
function getLanguagesInDocument(_document: TextDocument, regions: EmbeddedRegion[]): string[] {
|
||||
let result = [];
|
||||
for (let region of regions) {
|
||||
const result = [];
|
||||
for (const region of regions) {
|
||||
if (region.languageId && result.indexOf(region.languageId) === -1) {
|
||||
result.push(region.languageId);
|
||||
if (result.length === 3) {
|
||||
|
@ -147,8 +147,8 @@ function getLanguagesInDocument(_document: TextDocument, regions: EmbeddedRegion
|
|||
}
|
||||
|
||||
function getLanguageAtPosition(document: TextDocument, regions: EmbeddedRegion[], position: Position): string | undefined {
|
||||
let offset = document.offsetAt(position);
|
||||
for (let region of regions) {
|
||||
const offset = document.offsetAt(position);
|
||||
for (const region of regions) {
|
||||
if (region.start <= offset) {
|
||||
if (offset <= region.end) {
|
||||
return region.languageId;
|
||||
|
@ -162,10 +162,10 @@ function getLanguageAtPosition(document: TextDocument, regions: EmbeddedRegion[]
|
|||
|
||||
function getEmbeddedDocument(document: TextDocument, contents: EmbeddedRegion[], languageId: string, ignoreAttributeValues: boolean): TextDocument {
|
||||
let currentPos = 0;
|
||||
let oldContent = document.getText();
|
||||
const oldContent = document.getText();
|
||||
let result = '';
|
||||
let lastSuffix = '';
|
||||
for (let c of contents) {
|
||||
for (const c of contents) {
|
||||
if (c.languageId === languageId && (!ignoreAttributeValues || !c.attributeValue)) {
|
||||
result = substituteWithWhitespace(result, currentPos, c.start, oldContent, lastSuffix, getPrefix(c));
|
||||
result += oldContent.substring(c.start, c.end);
|
||||
|
@ -199,7 +199,7 @@ function substituteWithWhitespace(result: string, start: number, end: number, ol
|
|||
let accumulatedWS = 0;
|
||||
result += before;
|
||||
for (let i = start + before.length; i < end; i++) {
|
||||
let ch = oldContent[i];
|
||||
const ch = oldContent[i];
|
||||
if (ch === '\n' || ch === '\r') {
|
||||
// only write new lines, skip the whitespace
|
||||
accumulatedWS = 0;
|
||||
|
@ -225,7 +225,7 @@ function append(result: string, str: string, n: number): string {
|
|||
}
|
||||
|
||||
function getAttributeLanguage(attributeName: string): string | null {
|
||||
let match = attributeName.match(/^(style)$|^(on\w+)$/i);
|
||||
const match = attributeName.match(/^(style)$|^(on\w+)$/i);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
|
|
@ -8,14 +8,14 @@ import { pushAll } from '../utils/arrays';
|
|||
import { isEOL } from '../utils/strings';
|
||||
|
||||
export async function format(languageModes: LanguageModes, document: TextDocument, formatRange: Range, formattingOptions: FormattingOptions, settings: Settings | undefined, enabledModes: { [mode: string]: boolean }) {
|
||||
let result: TextEdit[] = [];
|
||||
const result: TextEdit[] = [];
|
||||
|
||||
let endPos = formatRange.end;
|
||||
const endPos = formatRange.end;
|
||||
let endOffset = document.offsetAt(endPos);
|
||||
let content = document.getText();
|
||||
const content = document.getText();
|
||||
if (endPos.character === 0 && endPos.line > 0 && endOffset !== content.length) {
|
||||
// if selection ends after a new line, exclude that new line
|
||||
let prevLineStart = document.offsetAt(Position.create(endPos.line - 1, 0));
|
||||
const prevLineStart = document.offsetAt(Position.create(endPos.line - 1, 0));
|
||||
while (isEOL(content, endOffset - 1) && endOffset > prevLineStart) {
|
||||
endOffset--;
|
||||
}
|
||||
|
@ -31,15 +31,15 @@ export async function format(languageModes: LanguageModes, document: TextDocumen
|
|||
// - no worrying of overlapping edits
|
||||
|
||||
// make sure we start in html
|
||||
let allRanges = languageModes.getModesInRange(document, formatRange);
|
||||
const allRanges = languageModes.getModesInRange(document, formatRange);
|
||||
let i = 0;
|
||||
let startPos = formatRange.start;
|
||||
let isHTML = (range: LanguageModeRange) => range.mode && range.mode.getId() === 'html';
|
||||
const isHTML = (range: LanguageModeRange) => range.mode && range.mode.getId() === 'html';
|
||||
|
||||
while (i < allRanges.length && !isHTML(allRanges[i])) {
|
||||
let range = allRanges[i];
|
||||
const range = allRanges[i];
|
||||
if (!range.attributeValue && range.mode && range.mode.format) {
|
||||
let edits = await range.mode.format(document, Range.create(startPos, range.end), formattingOptions, settings);
|
||||
const edits = await range.mode.format(document, Range.create(startPos, range.end), formattingOptions, settings);
|
||||
pushAll(result, edits);
|
||||
}
|
||||
startPos = range.end;
|
||||
|
@ -52,23 +52,23 @@ export async function format(languageModes: LanguageModes, document: TextDocumen
|
|||
formatRange = Range.create(startPos, formatRange.end);
|
||||
|
||||
// perform a html format and apply changes to a new document
|
||||
let htmlMode = languageModes.getMode('html')!;
|
||||
let htmlEdits = await htmlMode.format!(document, formatRange, formattingOptions, settings);
|
||||
let htmlFormattedContent = TextDocument.applyEdits(document, htmlEdits);
|
||||
let newDocument = TextDocument.create(document.uri + '.tmp', document.languageId, document.version, htmlFormattedContent);
|
||||
const htmlMode = languageModes.getMode('html')!;
|
||||
const htmlEdits = await htmlMode.format!(document, formatRange, formattingOptions, settings);
|
||||
const htmlFormattedContent = TextDocument.applyEdits(document, htmlEdits);
|
||||
const newDocument = TextDocument.create(document.uri + '.tmp', document.languageId, document.version, htmlFormattedContent);
|
||||
try {
|
||||
// run embedded formatters on html formatted content: - formatters see correct initial indent
|
||||
let afterFormatRangeLength = document.getText().length - document.offsetAt(formatRange.end); // length of unchanged content after replace range
|
||||
let newFormatRange = Range.create(formatRange.start, newDocument.positionAt(htmlFormattedContent.length - afterFormatRangeLength));
|
||||
let embeddedRanges = languageModes.getModesInRange(newDocument, newFormatRange);
|
||||
const afterFormatRangeLength = document.getText().length - document.offsetAt(formatRange.end); // length of unchanged content after replace range
|
||||
const newFormatRange = Range.create(formatRange.start, newDocument.positionAt(htmlFormattedContent.length - afterFormatRangeLength));
|
||||
const embeddedRanges = languageModes.getModesInRange(newDocument, newFormatRange);
|
||||
|
||||
let embeddedEdits: TextEdit[] = [];
|
||||
const embeddedEdits: TextEdit[] = [];
|
||||
|
||||
for (let r of embeddedRanges) {
|
||||
let mode = r.mode;
|
||||
for (const r of embeddedRanges) {
|
||||
const mode = r.mode;
|
||||
if (mode && mode.format && enabledModes[mode.getId()] && !r.attributeValue) {
|
||||
let edits = await mode.format(newDocument, r, formattingOptions, settings);
|
||||
for (let edit of edits) {
|
||||
const edits = await mode.format(newDocument, r, formattingOptions, settings);
|
||||
for (const edit of edits) {
|
||||
embeddedEdits.push(edit);
|
||||
}
|
||||
}
|
||||
|
@ -80,8 +80,8 @@ export async function format(languageModes: LanguageModes, document: TextDocumen
|
|||
}
|
||||
|
||||
// apply all embedded format edits and create a single edit for all changes
|
||||
let resultContent = TextDocument.applyEdits(newDocument, embeddedEdits);
|
||||
let resultReplaceText = resultContent.substring(document.offsetAt(formatRange.start), resultContent.length - afterFormatRangeLength);
|
||||
const resultContent = TextDocument.applyEdits(newDocument, embeddedEdits);
|
||||
const resultReplaceText = resultContent.substring(document.offsetAt(formatRange.start), resultContent.length - afterFormatRangeLength);
|
||||
|
||||
result.push(TextEdit.replace(formatRange, resultReplaceText));
|
||||
return result;
|
||||
|
|
|
@ -7,16 +7,16 @@ import { TextDocument, FoldingRange, Position, Range, LanguageModes, LanguageMod
|
|||
import { CancellationToken } from 'vscode-languageserver';
|
||||
|
||||
export async function getFoldingRanges(languageModes: LanguageModes, document: TextDocument, maxRanges: number | undefined, _cancellationToken: CancellationToken | null): Promise<FoldingRange[]> {
|
||||
let htmlMode = languageModes.getMode('html');
|
||||
let range = Range.create(Position.create(0, 0), Position.create(document.lineCount, 0));
|
||||
const htmlMode = languageModes.getMode('html');
|
||||
const range = Range.create(Position.create(0, 0), Position.create(document.lineCount, 0));
|
||||
let result: FoldingRange[] = [];
|
||||
if (htmlMode && htmlMode.getFoldingRanges) {
|
||||
result.push(... await htmlMode.getFoldingRanges(document));
|
||||
}
|
||||
|
||||
// cache folding ranges per mode
|
||||
let rangesPerMode: { [mode: string]: FoldingRange[] } = Object.create(null);
|
||||
let getRangesForMode = async (mode: LanguageMode) => {
|
||||
const rangesPerMode: { [mode: string]: FoldingRange[] } = Object.create(null);
|
||||
const getRangesForMode = async (mode: LanguageMode) => {
|
||||
if (mode.getFoldingRanges) {
|
||||
let ranges = rangesPerMode[mode.getId()];
|
||||
if (!Array.isArray(ranges)) {
|
||||
|
@ -28,9 +28,9 @@ export async function getFoldingRanges(languageModes: LanguageModes, document: T
|
|||
return [];
|
||||
};
|
||||
|
||||
let modeRanges = languageModes.getModesInRange(document, range);
|
||||
for (let modeRange of modeRanges) {
|
||||
let mode = modeRange.mode;
|
||||
const modeRanges = languageModes.getModesInRange(document, range);
|
||||
for (const modeRange of modeRanges) {
|
||||
const mode = modeRange.mode;
|
||||
if (mode && mode !== htmlMode && !modeRange.attributeValue) {
|
||||
const ranges = await getRangesForMode(mode);
|
||||
result.push(...ranges.filter(r => r.startLine >= modeRange.start.line && r.endLine < modeRange.end.line));
|
||||
|
@ -54,11 +54,11 @@ function limitRanges(ranges: FoldingRange[], maxRanges: number) {
|
|||
// compute each range's nesting level in 'nestingLevels'.
|
||||
// count the number of ranges for each level in 'nestingLevelCounts'
|
||||
let top: FoldingRange | undefined = undefined;
|
||||
let previous: FoldingRange[] = [];
|
||||
let nestingLevels: number[] = [];
|
||||
let nestingLevelCounts: number[] = [];
|
||||
const previous: FoldingRange[] = [];
|
||||
const nestingLevels: number[] = [];
|
||||
const nestingLevelCounts: number[] = [];
|
||||
|
||||
let setNestingLevel = (index: number, level: number) => {
|
||||
const setNestingLevel = (index: number, level: number) => {
|
||||
nestingLevels[index] = level;
|
||||
if (level < 30) {
|
||||
nestingLevelCounts[level] = (nestingLevelCounts[level] || 0) + 1;
|
||||
|
@ -67,7 +67,7 @@ function limitRanges(ranges: FoldingRange[], maxRanges: number) {
|
|||
|
||||
// compute nesting levels and sanitize
|
||||
for (let i = 0; i < ranges.length; i++) {
|
||||
let entry = ranges[i];
|
||||
const entry = ranges[i];
|
||||
if (!top) {
|
||||
top = entry;
|
||||
setNestingLevel(i, 0);
|
||||
|
@ -93,7 +93,7 @@ function limitRanges(ranges: FoldingRange[], maxRanges: number) {
|
|||
let entries = 0;
|
||||
let maxLevel = 0;
|
||||
for (let i = 0; i < nestingLevelCounts.length; i++) {
|
||||
let n = nestingLevelCounts[i];
|
||||
const n = nestingLevelCounts[i];
|
||||
if (n) {
|
||||
if (n + entries > maxRanges) {
|
||||
maxLevel = i;
|
||||
|
@ -102,9 +102,9 @@ function limitRanges(ranges: FoldingRange[], maxRanges: number) {
|
|||
entries += n;
|
||||
}
|
||||
}
|
||||
let result = [];
|
||||
const result = [];
|
||||
for (let i = 0; i < ranges.length; i++) {
|
||||
let level = nestingLevels[i];
|
||||
const level = nestingLevels[i];
|
||||
if (typeof level === 'number') {
|
||||
if (level < maxLevel || (level === maxLevel && entries++ < maxRanges)) {
|
||||
result.push(ranges[i]);
|
||||
|
|
|
@ -95,10 +95,10 @@ function getLanguageServiceHost(scriptKind: ts.ScriptKind) {
|
|||
|
||||
|
||||
export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocumentRegions>, languageId: 'javascript' | 'typescript', workspace: Workspace): LanguageMode {
|
||||
let jsDocuments = getLanguageModelCache<TextDocument>(10, 60, document => documentRegions.get(document).getEmbeddedDocument(languageId));
|
||||
const jsDocuments = getLanguageModelCache<TextDocument>(10, 60, document => documentRegions.get(document).getEmbeddedDocument(languageId));
|
||||
|
||||
const host = getLanguageServiceHost(languageId === 'javascript' ? ts.ScriptKind.JS : ts.ScriptKind.TS);
|
||||
let globalSettings: Settings = {};
|
||||
const globalSettings: Settings = {};
|
||||
|
||||
return {
|
||||
getId() {
|
||||
|
@ -122,12 +122,12 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async doComplete(document: TextDocument, position: Position, _documentContext: DocumentContext): Promise<CompletionList> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let offset = jsDocument.offsetAt(position);
|
||||
let completions = jsLanguageService.getCompletionsAtPosition(jsDocument.uri, offset, { includeExternalModuleExports: false, includeInsertTextCompletions: false });
|
||||
const offset = jsDocument.offsetAt(position);
|
||||
const completions = jsLanguageService.getCompletionsAtPosition(jsDocument.uri, offset, { includeExternalModuleExports: false, includeInsertTextCompletions: false });
|
||||
if (!completions) {
|
||||
return { isIncomplete: false, items: [] };
|
||||
}
|
||||
let replaceRange = convertRange(jsDocument, getWordAtText(jsDocument.getText(), offset, JS_WORD_REGEX));
|
||||
const replaceRange = convertRange(jsDocument, getWordAtText(jsDocument.getText(), offset, JS_WORD_REGEX));
|
||||
return {
|
||||
isIncomplete: false,
|
||||
items: completions.entries.map(entry => {
|
||||
|
@ -152,7 +152,7 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
if (isCompletionItemData(item.data)) {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let details = jsLanguageService.getCompletionEntryDetails(jsDocument.uri, item.data.offset, item.label, undefined, undefined, undefined, undefined);
|
||||
const details = jsLanguageService.getCompletionEntryDetails(jsDocument.uri, item.data.offset, item.label, undefined, undefined, undefined, undefined);
|
||||
if (details) {
|
||||
item.detail = ts.displayPartsToString(details.displayParts);
|
||||
item.documentation = ts.displayPartsToString(details.documentation);
|
||||
|
@ -164,7 +164,7 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async doHover(document: TextDocument, position: Position): Promise<Hover | null> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let info = jsLanguageService.getQuickInfoAtPosition(jsDocument.uri, jsDocument.offsetAt(position));
|
||||
const info = jsLanguageService.getQuickInfoAtPosition(jsDocument.uri, jsDocument.offsetAt(position));
|
||||
if (info) {
|
||||
const contents = ts.displayPartsToString(info.displayParts);
|
||||
return {
|
||||
|
@ -177,16 +177,16 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async doSignatureHelp(document: TextDocument, position: Position): Promise<SignatureHelp | null> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let signHelp = jsLanguageService.getSignatureHelpItems(jsDocument.uri, jsDocument.offsetAt(position), undefined);
|
||||
const signHelp = jsLanguageService.getSignatureHelpItems(jsDocument.uri, jsDocument.offsetAt(position), undefined);
|
||||
if (signHelp) {
|
||||
let ret: SignatureHelp = {
|
||||
const ret: SignatureHelp = {
|
||||
activeSignature: signHelp.selectedItemIndex,
|
||||
activeParameter: signHelp.argumentIndex,
|
||||
signatures: []
|
||||
};
|
||||
signHelp.items.forEach(item => {
|
||||
|
||||
let signature: SignatureInformation = {
|
||||
const signature: SignatureInformation = {
|
||||
label: '',
|
||||
documentation: undefined,
|
||||
parameters: []
|
||||
|
@ -194,8 +194,8 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
|
||||
signature.label += ts.displayPartsToString(item.prefixDisplayParts);
|
||||
item.parameters.forEach((p, i, a) => {
|
||||
let label = ts.displayPartsToString(p.displayParts);
|
||||
let parameter: ParameterInformation = {
|
||||
const label = ts.displayPartsToString(p.displayParts);
|
||||
const parameter: ParameterInformation = {
|
||||
label: label,
|
||||
documentation: ts.displayPartsToString(p.documentation)
|
||||
};
|
||||
|
@ -252,14 +252,14 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async findDocumentSymbols(document: TextDocument): Promise<SymbolInformation[]> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let items = jsLanguageService.getNavigationBarItems(jsDocument.uri);
|
||||
const items = jsLanguageService.getNavigationBarItems(jsDocument.uri);
|
||||
if (items) {
|
||||
let result: SymbolInformation[] = [];
|
||||
let existing = Object.create(null);
|
||||
let collectSymbols = (item: ts.NavigationBarItem, containerLabel?: string) => {
|
||||
let sig = item.text + item.kind + item.spans[0].start;
|
||||
const result: SymbolInformation[] = [];
|
||||
const existing = Object.create(null);
|
||||
const collectSymbols = (item: ts.NavigationBarItem, containerLabel?: string) => {
|
||||
const sig = item.text + item.kind + item.spans[0].start;
|
||||
if (item.kind !== 'script' && !existing[sig]) {
|
||||
let symbol: SymbolInformation = {
|
||||
const symbol: SymbolInformation = {
|
||||
name: item.text,
|
||||
kind: convertSymbolKind(item.kind),
|
||||
location: {
|
||||
|
@ -274,7 +274,7 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
}
|
||||
|
||||
if (item.childItems && item.childItems.length > 0) {
|
||||
for (let child of item.childItems) {
|
||||
for (const child of item.childItems) {
|
||||
collectSymbols(child, containerLabel);
|
||||
}
|
||||
}
|
||||
|
@ -289,7 +289,7 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async findDefinition(document: TextDocument, position: Position): Promise<Definition | null> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let definition = jsLanguageService.getDefinitionAtPosition(jsDocument.uri, jsDocument.offsetAt(position));
|
||||
const definition = jsLanguageService.getDefinitionAtPosition(jsDocument.uri, jsDocument.offsetAt(position));
|
||||
if (definition) {
|
||||
return definition.filter(d => d.fileName === jsDocument.uri).map(d => {
|
||||
return {
|
||||
|
@ -303,7 +303,7 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async findReferences(document: TextDocument, position: Position): Promise<Location[]> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let references = jsLanguageService.getReferencesAtPosition(jsDocument.uri, jsDocument.offsetAt(position));
|
||||
const references = jsLanguageService.getReferencesAtPosition(jsDocument.uri, jsDocument.offsetAt(position));
|
||||
if (references) {
|
||||
return references.filter(d => d.fileName === jsDocument.uri).map(d => {
|
||||
return {
|
||||
|
@ -328,21 +328,21 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
const jsDocument = documentRegions.get(document).getEmbeddedDocument('javascript', true);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
|
||||
let formatterSettings = settings && settings.javascript && settings.javascript.format;
|
||||
const formatterSettings = settings && settings.javascript && settings.javascript.format;
|
||||
|
||||
let initialIndentLevel = computeInitialIndent(document, range, formatParams);
|
||||
let formatSettings = convertOptions(formatParams, formatterSettings, initialIndentLevel + 1);
|
||||
let start = jsDocument.offsetAt(range.start);
|
||||
const initialIndentLevel = computeInitialIndent(document, range, formatParams);
|
||||
const formatSettings = convertOptions(formatParams, formatterSettings, initialIndentLevel + 1);
|
||||
const start = jsDocument.offsetAt(range.start);
|
||||
let end = jsDocument.offsetAt(range.end);
|
||||
let lastLineRange = null;
|
||||
if (range.end.line > range.start.line && (range.end.character === 0 || isWhitespaceOnly(jsDocument.getText().substr(end - range.end.character, range.end.character)))) {
|
||||
end -= range.end.character;
|
||||
lastLineRange = Range.create(Position.create(range.end.line, 0), range.end);
|
||||
}
|
||||
let edits = jsLanguageService.getFormattingEditsForRange(jsDocument.uri, start, end, formatSettings);
|
||||
const edits = jsLanguageService.getFormattingEditsForRange(jsDocument.uri, start, end, formatSettings);
|
||||
if (edits) {
|
||||
let result = [];
|
||||
for (let edit of edits) {
|
||||
const result = [];
|
||||
for (const edit of edits) {
|
||||
if (edit.span.start >= start && edit.span.start + edit.span.length <= end) {
|
||||
result.push({
|
||||
range: convertRange(jsDocument, edit.span),
|
||||
|
@ -363,15 +363,15 @@ export function getJavaScriptMode(documentRegions: LanguageModelCache<HTMLDocume
|
|||
async getFoldingRanges(document: TextDocument): Promise<FoldingRange[]> {
|
||||
const jsDocument = jsDocuments.get(document);
|
||||
const jsLanguageService = await host.getLanguageService(jsDocument);
|
||||
let spans = jsLanguageService.getOutliningSpans(jsDocument.uri);
|
||||
let ranges: FoldingRange[] = [];
|
||||
for (let span of spans) {
|
||||
let curr = convertRange(jsDocument, span.textSpan);
|
||||
let startLine = curr.start.line;
|
||||
let endLine = curr.end.line;
|
||||
const spans = jsLanguageService.getOutliningSpans(jsDocument.uri);
|
||||
const ranges: FoldingRange[] = [];
|
||||
for (const span of spans) {
|
||||
const curr = convertRange(jsDocument, span.textSpan);
|
||||
const startLine = curr.start.line;
|
||||
const endLine = curr.end.line;
|
||||
if (startLine < endLine) {
|
||||
let foldingRange: FoldingRange = { startLine, endLine };
|
||||
let match = document.getText(curr).match(/^\s*\/(?:(\/\s*#(?:end)?region\b)|(\*|\/))/);
|
||||
const foldingRange: FoldingRange = { startLine, endLine };
|
||||
const match = document.getText(curr).match(/^\s*\/(?:(\/\s*#(?:end)?region\b)|(\*|\/))/);
|
||||
if (match) {
|
||||
foldingRange.kind = match[1] ? FoldingRangeKind.Region : FoldingRangeKind.Comment;
|
||||
}
|
||||
|
@ -563,14 +563,14 @@ function convertOptions(options: FormattingOptions, formatSettings: any, initial
|
|||
}
|
||||
|
||||
function computeInitialIndent(document: TextDocument, range: Range, options: FormattingOptions) {
|
||||
let lineStart = document.offsetAt(Position.create(range.start.line, 0));
|
||||
let content = document.getText();
|
||||
const lineStart = document.offsetAt(Position.create(range.start.line, 0));
|
||||
const content = document.getText();
|
||||
|
||||
let i = lineStart;
|
||||
let nChars = 0;
|
||||
let tabSize = options.tabSize || 4;
|
||||
const tabSize = options.tabSize || 4;
|
||||
while (i < content.length) {
|
||||
let ch = content.charAt(i);
|
||||
const ch = content.charAt(i);
|
||||
if (ch === ' ') {
|
||||
nChars++;
|
||||
} else if (ch === '\t') {
|
||||
|
|
|
@ -111,7 +111,7 @@ export function getLanguageModes(supportedLanguages: { [languageId: string]: boo
|
|||
const htmlLanguageService = getHTMLLanguageService({ clientCapabilities, fileSystemProvider: requestService });
|
||||
const cssLanguageService = getCSSLanguageService({ clientCapabilities, fileSystemProvider: requestService });
|
||||
|
||||
let documentRegions = getLanguageModelCache<HTMLDocumentRegions>(10, 60, document => getDocumentRegions(htmlLanguageService, document));
|
||||
const documentRegions = getLanguageModelCache<HTMLDocumentRegions>(10, 60, document => getDocumentRegions(htmlLanguageService, document));
|
||||
|
||||
let modelCaches: LanguageModelCache<any>[] = [];
|
||||
modelCaches.push(documentRegions);
|
||||
|
@ -130,7 +130,7 @@ export function getLanguageModes(supportedLanguages: { [languageId: string]: boo
|
|||
htmlLanguageService.setDataProviders(true, dataProviders);
|
||||
},
|
||||
getModeAtPosition(document: TextDocument, position: Position): LanguageMode | undefined {
|
||||
let languageId = documentRegions.get(document).getLanguageAtPosition(position);
|
||||
const languageId = documentRegions.get(document).getLanguageAtPosition(position);
|
||||
if (languageId) {
|
||||
return modes[languageId];
|
||||
}
|
||||
|
@ -147,9 +147,9 @@ export function getLanguageModes(supportedLanguages: { [languageId: string]: boo
|
|||
});
|
||||
},
|
||||
getAllModesInDocument(document: TextDocument): LanguageMode[] {
|
||||
let result = [];
|
||||
for (let languageId of documentRegions.get(document).getLanguagesInDocument()) {
|
||||
let mode = modes[languageId];
|
||||
const result = [];
|
||||
for (const languageId of documentRegions.get(document).getLanguagesInDocument()) {
|
||||
const mode = modes[languageId];
|
||||
if (mode) {
|
||||
result.push(mode);
|
||||
}
|
||||
|
@ -157,9 +157,9 @@ export function getLanguageModes(supportedLanguages: { [languageId: string]: boo
|
|||
return result;
|
||||
},
|
||||
getAllModes(): LanguageMode[] {
|
||||
let result = [];
|
||||
for (let languageId in modes) {
|
||||
let mode = modes[languageId];
|
||||
const result = [];
|
||||
for (const languageId in modes) {
|
||||
const mode = modes[languageId];
|
||||
if (mode) {
|
||||
result.push(mode);
|
||||
}
|
||||
|
@ -171,14 +171,14 @@ export function getLanguageModes(supportedLanguages: { [languageId: string]: boo
|
|||
},
|
||||
onDocumentRemoved(document: TextDocument) {
|
||||
modelCaches.forEach(mc => mc.onDocumentRemoved(document));
|
||||
for (let mode in modes) {
|
||||
for (const mode in modes) {
|
||||
modes[mode].onDocumentRemoved(document);
|
||||
}
|
||||
},
|
||||
dispose(): void {
|
||||
modelCaches.forEach(mc => mc.dispose());
|
||||
modelCaches = [];
|
||||
for (let mode in modes) {
|
||||
for (const mode in modes) {
|
||||
modes[mode].dispose();
|
||||
}
|
||||
modes = {};
|
||||
|
|
|
@ -12,7 +12,7 @@ export async function getSelectionRanges(languageModes: LanguageModes, document:
|
|||
const htmlRange = await htmlMode!.getSelectionRange!(document, position);
|
||||
const mode = languageModes.getModeAtPosition(document, position);
|
||||
if (mode && mode.getSelectionRange) {
|
||||
let range = await mode.getSelectionRange(document, position);
|
||||
const range = await mode.getSelectionRange(document, position);
|
||||
let top = range;
|
||||
while (top.parent && insideRangeButNotSame(htmlRange.range, top.parent.range)) {
|
||||
top = top.parent;
|
||||
|
|
|
@ -23,7 +23,7 @@ export function newSemanticTokenProvider(languageModes: LanguageModes): Semantic
|
|||
const legend: { types: string[]; modifiers: string[] } = { types: [], modifiers: [] };
|
||||
const legendMappings: { [modeId: string]: LegendMapping } = {};
|
||||
|
||||
for (let mode of languageModes.getAllModes()) {
|
||||
for (const mode of languageModes.getAllModes()) {
|
||||
if (mode.getSemanticTokenLegend && mode.getSemanticTokens) {
|
||||
const modeLegend = mode.getSemanticTokenLegend();
|
||||
legendMappings[mode.getId()] = { types: createMapping(modeLegend.types, legend.types), modifiers: createMapping(modeLegend.modifiers, legend.modifiers) };
|
||||
|
@ -34,13 +34,13 @@ export function newSemanticTokenProvider(languageModes: LanguageModes): Semantic
|
|||
legend,
|
||||
async getSemanticTokens(document: TextDocument, ranges?: Range[]): Promise<number[]> {
|
||||
const allTokens: SemanticTokenData[] = [];
|
||||
for (let mode of languageModes.getAllModesInDocument(document)) {
|
||||
for (const mode of languageModes.getAllModesInDocument(document)) {
|
||||
if (mode.getSemanticTokens) {
|
||||
const mapping = legendMappings[mode.getId()];
|
||||
const tokens = await mode.getSemanticTokens(document);
|
||||
applyTypesMapping(tokens, mapping.types);
|
||||
applyModifiersMapping(tokens, mapping.modifiers);
|
||||
for (let token of tokens) {
|
||||
for (const token of tokens) {
|
||||
allTokens.push(token);
|
||||
}
|
||||
}
|
||||
|
@ -68,7 +68,7 @@ function createMapping(origLegend: string[], newLegend: string[]): number[] | un
|
|||
|
||||
function applyTypesMapping(tokens: SemanticTokenData[], typesMapping: number[] | undefined): void {
|
||||
if (typesMapping) {
|
||||
for (let token of tokens) {
|
||||
for (const token of tokens) {
|
||||
token.typeIdx = typesMapping[token.typeIdx];
|
||||
}
|
||||
}
|
||||
|
@ -76,7 +76,7 @@ function applyTypesMapping(tokens: SemanticTokenData[], typesMapping: number[] |
|
|||
|
||||
function applyModifiersMapping(tokens: SemanticTokenData[], modifiersMapping: number[] | undefined): void {
|
||||
if (modifiersMapping) {
|
||||
for (let token of tokens) {
|
||||
for (const token of tokens) {
|
||||
let modifierSet = token.modifierSet;
|
||||
if (modifierSet) {
|
||||
let index = 0;
|
||||
|
@ -109,7 +109,7 @@ function encodeTokens(tokens: SemanticTokenData[], ranges: Range[] | undefined,
|
|||
let prefLine = 0;
|
||||
let prevChar = 0;
|
||||
|
||||
let encodedResult: number[] = [];
|
||||
const encodedResult: number[] = [];
|
||||
|
||||
for (let k = 0; k < resultTokens.length && currRange; k++) {
|
||||
const curr = resultTokens[k];
|
||||
|
|
|
@ -149,7 +149,7 @@ export function normalizePath(parts: string[]): string {
|
|||
export function joinPath(uriString: string, ...paths: string[]): string {
|
||||
const uri = URI.parse(uriString);
|
||||
const parts = uri.path.split('/');
|
||||
for (let path of paths) {
|
||||
for (const path of paths) {
|
||||
parts.push(...path.split('/'));
|
||||
}
|
||||
return uri.with({ path: normalizePath(parts) }).toString();
|
||||
|
|
|
@ -19,7 +19,7 @@ export interface ItemDescription {
|
|||
}
|
||||
|
||||
export function assertCompletion(completions: CompletionList, expected: ItemDescription, document: TextDocument) {
|
||||
let matches = completions.items.filter(completion => {
|
||||
const matches = completions.items.filter(completion => {
|
||||
return completion.label === expected.label;
|
||||
});
|
||||
if (expected.notAvailable) {
|
||||
|
@ -28,7 +28,7 @@ export function assertCompletion(completions: CompletionList, expected: ItemDesc
|
|||
}
|
||||
|
||||
assert.strictEqual(matches.length, 1, `${expected.label} should only existing once: Actual: ${completions.items.map(c => c.label).join(', ')}`);
|
||||
let match = matches[0];
|
||||
const match = matches[0];
|
||||
if (expected.documentation) {
|
||||
assert.strictEqual(match.documentation, expected.documentation);
|
||||
}
|
||||
|
@ -47,28 +47,28 @@ export function assertCompletion(completions: CompletionList, expected: ItemDesc
|
|||
const testUri = 'test://test/test.html';
|
||||
|
||||
export async function testCompletionFor(value: string, expected: { count?: number; items?: ItemDescription[] }, uri = testUri, workspaceFolders?: WorkspaceFolder[]): Promise<void> {
|
||||
let offset = value.indexOf('|');
|
||||
const offset = value.indexOf('|');
|
||||
value = value.substr(0, offset) + value.substr(offset + 1);
|
||||
|
||||
let workspace = {
|
||||
const workspace = {
|
||||
settings: {},
|
||||
folders: workspaceFolders || [{ name: 'x', uri: uri.substr(0, uri.lastIndexOf('/')) }]
|
||||
};
|
||||
|
||||
let document = TextDocument.create(uri, 'html', 0, value);
|
||||
let position = document.positionAt(offset);
|
||||
const document = TextDocument.create(uri, 'html', 0, value);
|
||||
const position = document.positionAt(offset);
|
||||
const context = getDocumentContext(uri, workspace.folders);
|
||||
|
||||
const languageModes = getLanguageModes({ css: true, javascript: true }, workspace, ClientCapabilities.LATEST, getNodeFileFS());
|
||||
const mode = languageModes.getModeAtPosition(document, position)!;
|
||||
|
||||
let list = await mode.doComplete!(document, position, context);
|
||||
const list = await mode.doComplete!(document, position, context);
|
||||
|
||||
if (expected.count) {
|
||||
assert.strictEqual(list.items.length, expected.count);
|
||||
}
|
||||
if (expected.items) {
|
||||
for (let item of expected.items) {
|
||||
for (const item of expected.items) {
|
||||
assertCompletion(list, item, document);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ suite('HTML Document Context', () => {
|
|||
const docURI = 'file:///users/test/folder/test.html';
|
||||
const rootFolders = [{ name: '', uri: 'file:///users/test/' }];
|
||||
|
||||
let context = getDocumentContext(docURI, rootFolders);
|
||||
const context = getDocumentContext(docURI, rootFolders);
|
||||
assert.strictEqual(context.resolveReference('/', docURI), 'file:///users/test/');
|
||||
assert.strictEqual(context.resolveReference('/message.html', docURI), 'file:///users/test/message.html');
|
||||
assert.strictEqual(context.resolveReference('message.html', docURI), 'file:///users/test/folder/message.html');
|
||||
|
|
|
@ -15,7 +15,7 @@ import { getNodeFileFS } from '../node/nodeFs';
|
|||
suite('HTML Embedded Formatting', () => {
|
||||
|
||||
async function assertFormat(value: string, expected: string, options?: any, formatOptions?: FormattingOptions, message?: string): Promise<void> {
|
||||
let workspace = {
|
||||
const workspace = {
|
||||
settings: options,
|
||||
folders: [{ name: 'foo', uri: 'test://foo' }]
|
||||
};
|
||||
|
@ -32,21 +32,21 @@ suite('HTML Embedded Formatting', () => {
|
|||
rangeStartOffset = 0;
|
||||
rangeEndOffset = value.length;
|
||||
}
|
||||
let document = TextDocument.create('test://test/test.html', 'html', 0, value);
|
||||
let range = Range.create(document.positionAt(rangeStartOffset), document.positionAt(rangeEndOffset));
|
||||
const document = TextDocument.create('test://test/test.html', 'html', 0, value);
|
||||
const range = Range.create(document.positionAt(rangeStartOffset), document.positionAt(rangeEndOffset));
|
||||
if (!formatOptions) {
|
||||
formatOptions = FormattingOptions.create(2, true);
|
||||
}
|
||||
|
||||
let result = await format(languageModes, document, range, formatOptions, undefined, { css: true, javascript: true });
|
||||
const result = await format(languageModes, document, range, formatOptions, undefined, { css: true, javascript: true });
|
||||
|
||||
let actual = TextDocument.applyEdits(document, result);
|
||||
const actual = TextDocument.applyEdits(document, result);
|
||||
assert.strictEqual(actual, expected, message);
|
||||
}
|
||||
|
||||
async function assertFormatWithFixture(fixtureName: string, expectedPath: string, options?: any, formatOptions?: FormattingOptions): Promise<void> {
|
||||
let input = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'test', 'fixtures', 'inputs', fixtureName)).toString().replace(/\r\n/mg, '\n');
|
||||
let expected = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'test', 'fixtures', 'expected', expectedPath)).toString().replace(/\r\n/mg, '\n');
|
||||
const input = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'test', 'fixtures', 'inputs', fixtureName)).toString().replace(/\r\n/mg, '\n');
|
||||
const expected = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'test', 'fixtures', 'expected', expectedPath)).toString().replace(/\r\n/mg, '\n');
|
||||
await assertFormat(input, expected, options, formatOptions, expectedPath);
|
||||
}
|
||||
|
||||
|
@ -85,7 +85,7 @@ suite('HTML Embedded Formatting', () => {
|
|||
});
|
||||
|
||||
test('EndWithNewline', async () => {
|
||||
let options = {
|
||||
const options = {
|
||||
html: {
|
||||
format: {
|
||||
endWithNewline: true
|
||||
|
@ -160,7 +160,7 @@ suite('HTML Embedded Formatting', () => {
|
|||
);
|
||||
});
|
||||
test('#58435', async () => {
|
||||
let options = {
|
||||
const options = {
|
||||
html: {
|
||||
format: {
|
||||
contentUnformatted: 'textarea'
|
||||
|
|
|
@ -15,7 +15,7 @@ async function assertRanges(content: string, expected: (number | string)[][]): P
|
|||
const offset = content.indexOf('|');
|
||||
content = content.substr(0, offset) + content.substr(offset + 1);
|
||||
|
||||
let workspace = {
|
||||
const workspace = {
|
||||
settings: {},
|
||||
folders: [{ name: 'foo', uri: 'test://foo' }]
|
||||
};
|
||||
|
|
|
@ -28,7 +28,7 @@ async function assertTokens(lines: string[], expected: ExpectedToken[], ranges?:
|
|||
const legend = semanticTokensProvider.legend;
|
||||
const actual = await semanticTokensProvider.getSemanticTokens(document, ranges);
|
||||
|
||||
let actualRanges = [];
|
||||
const actualRanges = [];
|
||||
let lastLine = 0;
|
||||
let lastCharacter = 0;
|
||||
for (let i = 0; i < actual.length; i += 5) {
|
||||
|
|
|
@ -40,7 +40,7 @@ function _divideAndMerge<T>(data: T[], compare: (a: T, b: T) => number): void {
|
|||
let rightIdx = 0;
|
||||
let i = 0;
|
||||
while (leftIdx < left.length && rightIdx < right.length) {
|
||||
let ret = compare(left[leftIdx], right[rightIdx]);
|
||||
const ret = compare(left[leftIdx], right[rightIdx]);
|
||||
if (ret <= 0) {
|
||||
// smaller_equal -> take left to preserve order
|
||||
data[i++] = left[leftIdx++];
|
||||
|
@ -62,8 +62,8 @@ export function binarySearch<T>(array: T[], key: T, comparator: (op1: T, op2: T)
|
|||
high = array.length - 1;
|
||||
|
||||
while (low <= high) {
|
||||
let mid = ((low + high) / 2) | 0;
|
||||
let comp = comparator(array[mid], key);
|
||||
const mid = ((low + high) / 2) | 0;
|
||||
const comp = comparator(array[mid], key);
|
||||
if (comp < 0) {
|
||||
low = mid + 1;
|
||||
} else if (comp > 0) {
|
||||
|
|
|
@ -10,7 +10,7 @@ import { resolvePath } from '../requests';
|
|||
|
||||
export function getDocumentContext(documentUri: string, workspaceFolders: WorkspaceFolder[]): DocumentContext {
|
||||
function getRootFolder(): string | undefined {
|
||||
for (let folder of workspaceFolders) {
|
||||
for (const folder of workspaceFolders) {
|
||||
let folderURI = folder.uri;
|
||||
if (!endsWith(folderURI, '/')) {
|
||||
folderURI = folderURI + '/';
|
||||
|
@ -25,7 +25,7 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
|
|||
return {
|
||||
resolveReference: (ref: string, base = documentUri) => {
|
||||
if (ref[0] === '/') { // resolve absolute path against the current workspace folder
|
||||
let folderUri = getRootFolder();
|
||||
const folderUri = getRootFolder();
|
||||
if (folderUri) {
|
||||
return folderUri + ref.substr(1);
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import { RuntimeEnvironment } from '../htmlServer';
|
|||
|
||||
export function formatError(message: string, err: any): string {
|
||||
if (err instanceof Error) {
|
||||
let error = <Error>err;
|
||||
const error = <Error>err;
|
||||
return `${message}: ${error.message}\n${error.stack}`;
|
||||
} else if (typeof err === 'string') {
|
||||
return `${message}: ${err}`;
|
||||
|
|
|
@ -8,11 +8,11 @@ export function getWordAtText(text: string, offset: number, wordDefinition: RegE
|
|||
while (lineStart > 0 && !isNewlineCharacter(text.charCodeAt(lineStart - 1))) {
|
||||
lineStart--;
|
||||
}
|
||||
let offsetInLine = offset - lineStart;
|
||||
let lineText = text.substr(lineStart);
|
||||
const offsetInLine = offset - lineStart;
|
||||
const lineText = text.substr(lineStart);
|
||||
|
||||
// make a copy of the regex as to not keep the state
|
||||
let flags = wordDefinition.ignoreCase ? 'gi' : 'g';
|
||||
const flags = wordDefinition.ignoreCase ? 'gi' : 'g';
|
||||
wordDefinition = new RegExp(wordDefinition.source, flags);
|
||||
|
||||
let match = wordDefinition.exec(lineText);
|
||||
|
@ -41,7 +41,7 @@ export function startsWith(haystack: string, needle: string): boolean {
|
|||
}
|
||||
|
||||
export function endsWith(haystack: string, needle: string): boolean {
|
||||
let diff = haystack.length - needle.length;
|
||||
const diff = haystack.length - needle.length;
|
||||
if (diff > 0) {
|
||||
return haystack.indexOf(needle, diff) === diff;
|
||||
} else if (diff === 0) {
|
||||
|
|
|
@ -259,7 +259,7 @@
|
|||
firstZoom();
|
||||
}
|
||||
|
||||
let delta = e.deltaY > 0 ? 1 : -1;
|
||||
const delta = e.deltaY > 0 ? 1 : -1;
|
||||
updateScale(scale * (1 - delta * SCALE_PINCH_FACTOR));
|
||||
}, { passive: false });
|
||||
|
||||
|
|
|
@ -9,7 +9,7 @@ import * as vscode from 'vscode';
|
|||
import { jupyterCellOutputToCellOutput, jupyterNotebookModelToNotebookData } from '../deserializers';
|
||||
|
||||
function deepStripProperties(obj: any, props: string[]) {
|
||||
for (let prop in obj) {
|
||||
for (const prop in obj) {
|
||||
if (obj[prop]) {
|
||||
delete obj[prop];
|
||||
} else if (typeof obj[prop] === 'object') {
|
||||
|
|
|
@ -33,7 +33,7 @@ function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: strin
|
|||
|
||||
const buildNames: string[] = ['build', 'compile', 'watch'];
|
||||
function isBuildTask(name: string): boolean {
|
||||
for (let buildName of buildNames) {
|
||||
for (const buildName of buildNames) {
|
||||
if (name.indexOf(buildName) !== -1) {
|
||||
return true;
|
||||
}
|
||||
|
@ -43,7 +43,7 @@ function isBuildTask(name: string): boolean {
|
|||
|
||||
const testNames: string[] = ['test'];
|
||||
function isTestTask(name: string): boolean {
|
||||
for (let testName of testNames) {
|
||||
for (const testName of testNames) {
|
||||
if (name.indexOf(testName) !== -1) {
|
||||
return true;
|
||||
}
|
||||
|
@ -68,7 +68,7 @@ function showError() {
|
|||
|
||||
async function findJakeCommand(rootPath: string): Promise<string> {
|
||||
let jakeCommand: string;
|
||||
let platform = process.platform;
|
||||
const platform = process.platform;
|
||||
if (platform === 'win32' && await exists(path.join(rootPath!, 'node_modules', '.bin', 'jake.cmd'))) {
|
||||
jakeCommand = path.join('.', 'node_modules', '.bin', 'jake.cmd');
|
||||
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(rootPath!, 'node_modules', '.bin', 'jake'))) {
|
||||
|
@ -103,7 +103,7 @@ class FolderDetector {
|
|||
}
|
||||
|
||||
public start(): void {
|
||||
let pattern = path.join(this._workspaceFolder.uri.fsPath, '{node_modules,Jakefile,Jakefile.js}');
|
||||
const pattern = path.join(this._workspaceFolder.uri.fsPath, '{node_modules,Jakefile,Jakefile.js}');
|
||||
this.fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
|
||||
this.fileWatcher.onDidChange(() => this.promise = undefined);
|
||||
this.fileWatcher.onDidCreate(() => this.promise = undefined);
|
||||
|
@ -124,17 +124,17 @@ class FolderDetector {
|
|||
public async getTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
|
||||
const jakeTask = (<any>_task.definition).task;
|
||||
if (jakeTask) {
|
||||
let kind: JakeTaskDefinition = (<any>_task.definition);
|
||||
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
let task = new vscode.Task(kind, this.workspaceFolder, jakeTask, 'jake', new vscode.ShellExecution(await this._jakeCommand, [jakeTask], options));
|
||||
const kind: JakeTaskDefinition = (<any>_task.definition);
|
||||
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
const task = new vscode.Task(kind, this.workspaceFolder, jakeTask, 'jake', new vscode.ShellExecution(await this._jakeCommand, [jakeTask], options));
|
||||
return task;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async computeTasks(): Promise<vscode.Task[]> {
|
||||
let rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
|
||||
let emptyTasks: vscode.Task[] = [];
|
||||
const rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
|
||||
const emptyTasks: vscode.Task[] = [];
|
||||
if (!rootPath) {
|
||||
return emptyTasks;
|
||||
}
|
||||
|
@ -146,32 +146,32 @@ class FolderDetector {
|
|||
}
|
||||
}
|
||||
|
||||
let commandLine = `${await this._jakeCommand} --tasks`;
|
||||
const commandLine = `${await this._jakeCommand} --tasks`;
|
||||
try {
|
||||
let { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
|
||||
const { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
|
||||
if (stderr) {
|
||||
getOutputChannel().appendLine(stderr);
|
||||
showError();
|
||||
}
|
||||
let result: vscode.Task[] = [];
|
||||
const result: vscode.Task[] = [];
|
||||
if (stdout) {
|
||||
let lines = stdout.split(/\r{0,1}\n/);
|
||||
for (let line of lines) {
|
||||
const lines = stdout.split(/\r{0,1}\n/);
|
||||
for (const line of lines) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
let regExp = /^jake\s+([^\s]+)\s/g;
|
||||
let matches = regExp.exec(line);
|
||||
const regExp = /^jake\s+([^\s]+)\s/g;
|
||||
const matches = regExp.exec(line);
|
||||
if (matches && matches.length === 2) {
|
||||
let taskName = matches[1];
|
||||
let kind: JakeTaskDefinition = {
|
||||
const taskName = matches[1];
|
||||
const kind: JakeTaskDefinition = {
|
||||
type: 'jake',
|
||||
task: taskName
|
||||
};
|
||||
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
let task = new vscode.Task(kind, taskName, 'jake', new vscode.ShellExecution(`${await this._jakeCommand} ${taskName}`, options));
|
||||
const options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
|
||||
const task = new vscode.Task(kind, taskName, 'jake', new vscode.ShellExecution(`${await this._jakeCommand} ${taskName}`, options));
|
||||
result.push(task);
|
||||
let lowerCaseLine = line.toLowerCase();
|
||||
const lowerCaseLine = line.toLowerCase();
|
||||
if (isBuildTask(lowerCaseLine)) {
|
||||
task.group = vscode.TaskGroup.Build;
|
||||
} else if (isTestTask(lowerCaseLine)) {
|
||||
|
@ -182,7 +182,7 @@ class FolderDetector {
|
|||
}
|
||||
return result;
|
||||
} catch (err) {
|
||||
let channel = getOutputChannel();
|
||||
const channel = getOutputChannel();
|
||||
if (err.stderr) {
|
||||
channel.appendLine(err.stderr);
|
||||
}
|
||||
|
@ -212,7 +212,7 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
public start(): void {
|
||||
let folders = vscode.workspace.workspaceFolders;
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (folders) {
|
||||
this.updateWorkspaceFolders(folders, []);
|
||||
}
|
||||
|
@ -229,15 +229,15 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
private updateWorkspaceFolders(added: readonly vscode.WorkspaceFolder[], removed: readonly vscode.WorkspaceFolder[]): void {
|
||||
for (let remove of removed) {
|
||||
let detector = this.detectors.get(remove.uri.toString());
|
||||
for (const remove of removed) {
|
||||
const detector = this.detectors.get(remove.uri.toString());
|
||||
if (detector) {
|
||||
detector.dispose();
|
||||
this.detectors.delete(remove.uri.toString());
|
||||
}
|
||||
}
|
||||
for (let add of added) {
|
||||
let detector = new FolderDetector(add, findJakeCommand(add.uri.fsPath));
|
||||
for (const add of added) {
|
||||
const detector = new FolderDetector(add, findJakeCommand(add.uri.fsPath));
|
||||
this.detectors.set(add.uri.toString(), detector);
|
||||
if (detector.isEnabled()) {
|
||||
detector.start();
|
||||
|
@ -247,15 +247,15 @@ class TaskDetector {
|
|||
}
|
||||
|
||||
private updateConfiguration(): void {
|
||||
for (let detector of this.detectors.values()) {
|
||||
for (const detector of this.detectors.values()) {
|
||||
detector.dispose();
|
||||
this.detectors.delete(detector.workspaceFolder.uri.toString());
|
||||
}
|
||||
let folders = vscode.workspace.workspaceFolders;
|
||||
const folders = vscode.workspace.workspaceFolders;
|
||||
if (folders) {
|
||||
for (let folder of folders) {
|
||||
for (const folder of folders) {
|
||||
if (!this.detectors.has(folder.uri.toString())) {
|
||||
let detector = new FolderDetector(folder, findJakeCommand(folder.uri.fsPath));
|
||||
const detector = new FolderDetector(folder, findJakeCommand(folder.uri.fsPath));
|
||||
this.detectors.set(folder.uri.toString(), detector);
|
||||
if (detector.isEnabled()) {
|
||||
detector.start();
|
||||
|
@ -294,13 +294,13 @@ class TaskDetector {
|
|||
} else if (this.detectors.size === 1) {
|
||||
return this.detectors.values().next().value.getTasks();
|
||||
} else {
|
||||
let promises: Promise<vscode.Task[]>[] = [];
|
||||
for (let detector of this.detectors.values()) {
|
||||
const promises: Promise<vscode.Task[]>[] = [];
|
||||
for (const detector of this.detectors.values()) {
|
||||
promises.push(detector.getTasks().then((value) => value, () => []));
|
||||
}
|
||||
return Promise.all(promises).then((values) => {
|
||||
let result: vscode.Task[] = [];
|
||||
for (let tasks of values) {
|
||||
const result: vscode.Task[] = [];
|
||||
for (const tasks of values) {
|
||||
if (tasks && tasks.length > 0) {
|
||||
result.push(...tasks);
|
||||
}
|
||||
|
|
|
@ -69,7 +69,7 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
|
|||
|
||||
function getSchemaRequestService(handledSchemas: string[] = ['https', 'http', 'file']) {
|
||||
const builtInHandlers: { [protocol: string]: RequestService | undefined } = {};
|
||||
for (let protocol of handledSchemas) {
|
||||
for (const protocol of handledSchemas) {
|
||||
if (protocol === 'file') {
|
||||
builtInHandlers[protocol] = runtime.file;
|
||||
} else if (protocol === 'http' || protocol === 'https') {
|
||||
|
@ -250,7 +250,7 @@ export function startServer(connection: Connection, runtime: RuntimeEnvironment)
|
|||
|
||||
// The settings have changed. Is send on server activation as well.
|
||||
connection.onDidChangeConfiguration((change) => {
|
||||
let settings = <Settings>change.settings;
|
||||
const settings = <Settings>change.settings;
|
||||
if (runtime.configureHttpRequests) {
|
||||
runtime.configureHttpRequests(settings?.http?.proxy, !!settings.http?.proxyStrictSSL);
|
||||
}
|
||||
|
|
|
@ -18,10 +18,10 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
let cleanupInterval: NodeJS.Timer | undefined = undefined;
|
||||
if (cleanupIntervalTimeInSec > 0) {
|
||||
cleanupInterval = setInterval(() => {
|
||||
let cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
|
||||
let uris = Object.keys(languageModels);
|
||||
for (let uri of uris) {
|
||||
let languageModelInfo = languageModels[uri];
|
||||
const cutoffTime = Date.now() - cleanupIntervalTimeInSec * 1000;
|
||||
const uris = Object.keys(languageModels);
|
||||
for (const uri of uris) {
|
||||
const languageModelInfo = languageModels[uri];
|
||||
if (languageModelInfo.cTime < cutoffTime) {
|
||||
delete languageModels[uri];
|
||||
nModels--;
|
||||
|
@ -32,14 +32,14 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
|
||||
return {
|
||||
get(document: TextDocument): T {
|
||||
let version = document.version;
|
||||
let languageId = document.languageId;
|
||||
let languageModelInfo = languageModels[document.uri];
|
||||
const version = document.version;
|
||||
const languageId = document.languageId;
|
||||
const languageModelInfo = languageModels[document.uri];
|
||||
if (languageModelInfo && languageModelInfo.version === version && languageModelInfo.languageId === languageId) {
|
||||
languageModelInfo.cTime = Date.now();
|
||||
return languageModelInfo.languageModel;
|
||||
}
|
||||
let languageModel = parse(document);
|
||||
const languageModel = parse(document);
|
||||
languageModels[document.uri] = { languageModel, version, languageId, cTime: Date.now() };
|
||||
if (!languageModelInfo) {
|
||||
nModels++;
|
||||
|
@ -48,8 +48,8 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
if (nModels === maxEntries) {
|
||||
let oldestTime = Number.MAX_VALUE;
|
||||
let oldestUri = null;
|
||||
for (let uri in languageModels) {
|
||||
let languageModelInfo = languageModels[uri];
|
||||
for (const uri in languageModels) {
|
||||
const languageModelInfo = languageModels[uri];
|
||||
if (languageModelInfo.cTime < oldestTime) {
|
||||
oldestUri = uri;
|
||||
oldestTime = languageModelInfo.cTime;
|
||||
|
@ -64,7 +64,7 @@ export function getLanguageModelCache<T>(maxEntries: number, cleanupIntervalTime
|
|||
|
||||
},
|
||||
onDocumentRemoved(document: TextDocument) {
|
||||
let uri = document.uri;
|
||||
const uri = document.uri;
|
||||
if (languageModels[uri]) {
|
||||
delete languageModels[uri];
|
||||
nModels--;
|
||||
|
|
|
@ -8,7 +8,7 @@ import { RuntimeEnvironment } from '../jsonServer';
|
|||
|
||||
export function formatError(message: string, err: any): string {
|
||||
if (err instanceof Error) {
|
||||
let error = <Error>err;
|
||||
const error = <Error>err;
|
||||
return `${message}: ${error.message}\n${error.stack}`;
|
||||
} else if (typeof err === 'string') {
|
||||
return `${message}: ${err}`;
|
||||
|
@ -47,7 +47,7 @@ export function runSafe<T, E>(runtime: RuntimeEnvironment, func: () => T, errorV
|
|||
resolve(cancelValue());
|
||||
} else {
|
||||
try {
|
||||
let result = func();
|
||||
const result = func();
|
||||
if (token.isCancellationRequested) {
|
||||
resolve(cancelValue());
|
||||
return;
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
* Determines if haystack ends with needle.
|
||||
*/
|
||||
export function endsWith(haystack: string, needle: string): boolean {
|
||||
let diff = haystack.length - needle.length;
|
||||
const diff = haystack.length - needle.length;
|
||||
if (diff > 0) {
|
||||
return haystack.lastIndexOf(needle) === diff;
|
||||
} else if (diff === 0) {
|
||||
|
|
|
@ -240,7 +240,7 @@ function isBlockElement(token: Token): boolean {
|
|||
function getFirstChildHeader(document: SkinnyTextDocument, header?: TocEntry, toc?: readonly TocEntry[]): vscode.Position | undefined {
|
||||
let childRange: vscode.Position | undefined;
|
||||
if (header && toc) {
|
||||
let children = toc.filter(t => header.sectionLocation.range.contains(t.sectionLocation.range) && t.sectionLocation.range.start.line > header.sectionLocation.range.start.line).sort((t1, t2) => t1.line - t2.line);
|
||||
const children = toc.filter(t => header.sectionLocation.range.contains(t.sectionLocation.range) && t.sectionLocation.range.start.line > header.sectionLocation.range.start.line).sort((t1, t2) => t1.line - t2.line);
|
||||
if (children.length > 0) {
|
||||
childRange = children[0].sectionLocation.range.start;
|
||||
const lineText = document.lineAt(childRange.line - 1).text;
|
||||
|
|
|
@ -14,7 +14,7 @@ export const joinLines = (...args: string[]) =>
|
|||
export const CURSOR = '$$CURSOR$$';
|
||||
|
||||
export function getCursorPositions(contents: string, doc: InMemoryDocument): vscode.Position[] {
|
||||
let positions: vscode.Position[] = [];
|
||||
const positions: vscode.Position[] = [];
|
||||
let index = 0;
|
||||
let wordLength = 0;
|
||||
while (index !== -1) {
|
||||
|
|
|
@ -22,7 +22,7 @@ enum OpenMarkdownLinks {
|
|||
}
|
||||
|
||||
export function resolveDocumentLink(href: string, markdownFile: vscode.Uri): vscode.Uri {
|
||||
let [hrefPath, fragment] = href.split('#').map(c => decodeURIComponent(c));
|
||||
const [hrefPath, fragment] = href.split('#').map(c => decodeURIComponent(c));
|
||||
|
||||
if (hrefPath[0] === '/') {
|
||||
// Absolute path. Try to resolve relative to the workspace
|
||||
|
|
|
@ -52,7 +52,7 @@ export default class MergeConflictCodeLensProvider implements vscode.CodeLensPro
|
|||
return null;
|
||||
}
|
||||
|
||||
let conflicts = await this.tracker.getConflicts(document);
|
||||
const conflicts = await this.tracker.getConflicts(document);
|
||||
const conflictsCount = conflicts?.length ?? 0;
|
||||
vscode.commands.executeCommand('setContext', 'mergeConflictsCount', conflictsCount);
|
||||
|
||||
|
@ -60,28 +60,28 @@ export default class MergeConflictCodeLensProvider implements vscode.CodeLensPro
|
|||
return null;
|
||||
}
|
||||
|
||||
let items: vscode.CodeLens[] = [];
|
||||
const items: vscode.CodeLens[] = [];
|
||||
|
||||
conflicts.forEach(conflict => {
|
||||
let acceptCurrentCommand: vscode.Command = {
|
||||
const acceptCurrentCommand: vscode.Command = {
|
||||
command: 'merge-conflict.accept.current',
|
||||
title: localize('acceptCurrentChange', 'Accept Current Change'),
|
||||
arguments: ['known-conflict', conflict]
|
||||
};
|
||||
|
||||
let acceptIncomingCommand: vscode.Command = {
|
||||
const acceptIncomingCommand: vscode.Command = {
|
||||
command: 'merge-conflict.accept.incoming',
|
||||
title: localize('acceptIncomingChange', 'Accept Incoming Change'),
|
||||
arguments: ['known-conflict', conflict]
|
||||
};
|
||||
|
||||
let acceptBothCommand: vscode.Command = {
|
||||
const acceptBothCommand: vscode.Command = {
|
||||
command: 'merge-conflict.accept.both',
|
||||
title: localize('acceptBothChanges', 'Accept Both Changes'),
|
||||
arguments: ['known-conflict', conflict]
|
||||
};
|
||||
|
||||
let diffCommand: vscode.Command = {
|
||||
const diffCommand: vscode.Command = {
|
||||
command: 'merge-conflict.compare',
|
||||
title: localize('compareChanges', 'Compare Changes'),
|
||||
arguments: [conflict]
|
||||
|
|
|
@ -107,8 +107,8 @@ export default class CommandHandler implements vscode.Disposable {
|
|||
|
||||
const scheme = editor.document.uri.scheme;
|
||||
let range = conflict.current.content;
|
||||
let leftRanges = conflicts.map(conflict => [conflict.current.content, conflict.range]);
|
||||
let rightRanges = conflicts.map(conflict => [conflict.incoming.content, conflict.range]);
|
||||
const leftRanges = conflicts.map(conflict => [conflict.current.content, conflict.range]);
|
||||
const rightRanges = conflicts.map(conflict => [conflict.incoming.content, conflict.range]);
|
||||
|
||||
const leftUri = editor.document.uri.with({
|
||||
scheme: ContentProvider.scheme,
|
||||
|
@ -120,7 +120,7 @@ export default class CommandHandler implements vscode.Disposable {
|
|||
const rightUri = leftUri.with({ query: JSON.stringify({ scheme, ranges: rightRanges }) });
|
||||
|
||||
let mergeConflictLineOffsets = 0;
|
||||
for (let nextconflict of conflicts) {
|
||||
for (const nextconflict of conflicts) {
|
||||
if (nextconflict.range.isEqual(conflict.range)) {
|
||||
break;
|
||||
} else {
|
||||
|
@ -158,7 +158,7 @@ export default class CommandHandler implements vscode.Disposable {
|
|||
}
|
||||
|
||||
async acceptSelection(editor: vscode.TextEditor): Promise<void> {
|
||||
let conflict = await this.findConflictContainingSelection(editor);
|
||||
const conflict = await this.findConflictContainingSelection(editor);
|
||||
|
||||
if (!conflict) {
|
||||
vscode.window.showWarningMessage(localize('cursorNotInConflict', 'Editor cursor is not within a merge conflict'));
|
||||
|
@ -202,7 +202,7 @@ export default class CommandHandler implements vscode.Disposable {
|
|||
}
|
||||
|
||||
private async navigate(editor: vscode.TextEditor, direction: NavigationDirection): Promise<void> {
|
||||
let navigationResult = await this.findConflictForNavigation(editor, direction);
|
||||
const navigationResult = await this.findConflictForNavigation(editor, direction);
|
||||
|
||||
if (!navigationResult) {
|
||||
// Check for autoNavigateNextConflict, if it's enabled(which indicating no conflict remain), then do not show warning
|
||||
|
@ -258,7 +258,7 @@ export default class CommandHandler implements vscode.Disposable {
|
|||
}
|
||||
|
||||
private async acceptAll(type: interfaces.CommitType, editor: vscode.TextEditor): Promise<void> {
|
||||
let conflicts = await this.tracker.getConflicts(editor.document);
|
||||
const conflicts = await this.tracker.getConflicts(editor.document);
|
||||
|
||||
if (!conflicts || conflicts.length === 0) {
|
||||
vscode.window.showWarningMessage(localize('noConflicts', 'No merge conflicts found in this file'));
|
||||
|
@ -323,7 +323,7 @@ export default class CommandHandler implements vscode.Disposable {
|
|||
return null;
|
||||
}
|
||||
|
||||
let selection = editor.selection.active;
|
||||
const selection = editor.selection.active;
|
||||
if (conflicts.length === 1) {
|
||||
if (conflicts[0].range.contains(selection)) {
|
||||
return {
|
||||
|
|
|
@ -32,7 +32,7 @@ export default class MergeConflictContentProvider implements vscode.TextDocument
|
|||
let lastPosition = new vscode.Position(0, 0);
|
||||
|
||||
ranges.forEach(rangeObj => {
|
||||
let [conflictRange, fullRange] = rangeObj;
|
||||
const [conflictRange, fullRange] = rangeObj;
|
||||
const [start, end] = conflictRange;
|
||||
const [fullStart, fullEnd] = fullRange;
|
||||
|
||||
|
@ -41,7 +41,7 @@ export default class MergeConflictContentProvider implements vscode.TextDocument
|
|||
lastPosition = new vscode.Position(fullEnd.line, fullEnd.character);
|
||||
});
|
||||
|
||||
let documentEnd = document.lineAt(document.lineCount - 1).range.end;
|
||||
const documentEnd = document.lineAt(document.lineCount - 1).range.end;
|
||||
text += document.getText(new vscode.Range(lastPosition.line, lastPosition.character, documentEnd.line, documentEnd.character));
|
||||
|
||||
return text;
|
||||
|
|
|
@ -35,7 +35,7 @@ export class Delayer<T> {
|
|||
}).then(() => {
|
||||
this.completionPromise = null;
|
||||
this.onSuccess = null;
|
||||
let result = this.task!();
|
||||
const result = this.task!();
|
||||
this.task = null;
|
||||
return result;
|
||||
});
|
||||
|
@ -56,7 +56,7 @@ export class Delayer<T> {
|
|||
return null;
|
||||
}
|
||||
this.cancelTimeout();
|
||||
let result = this.completionPromise;
|
||||
const result = this.completionPromise;
|
||||
this.onSuccess!(undefined);
|
||||
return result;
|
||||
}
|
||||
|
|
|
@ -45,11 +45,11 @@ export class DocumentMergeConflict implements interfaces.IDocumentMergeConflict
|
|||
// ]
|
||||
if (type === interfaces.CommitType.Current) {
|
||||
// Replace [ Conflict Range ] with [ Current Content ]
|
||||
let content = document.getText(this.current.content);
|
||||
const content = document.getText(this.current.content);
|
||||
this.replaceRangeWithContent(content, edit);
|
||||
}
|
||||
else if (type === interfaces.CommitType.Incoming) {
|
||||
let content = document.getText(this.incoming.content);
|
||||
const content = document.getText(this.incoming.content);
|
||||
this.replaceRangeWithContent(content, edit);
|
||||
}
|
||||
else if (type === interfaces.CommitType.Both) {
|
||||
|
|
|
@ -50,7 +50,7 @@ export default class DocumentMergeConflictTracker implements vscode.Disposable,
|
|||
getConflicts(document: vscode.TextDocument, origin: string): PromiseLike<interfaces.IDocumentMergeConflict[]> {
|
||||
// Attempt from cache
|
||||
|
||||
let key = this.getCacheKey(document);
|
||||
const key = this.getCacheKey(document);
|
||||
|
||||
if (!key) {
|
||||
// Document doesn't have a uri, can't cache it, so return
|
||||
|
@ -67,7 +67,7 @@ export default class DocumentMergeConflictTracker implements vscode.Disposable,
|
|||
}
|
||||
|
||||
return cacheItem.delayTask.trigger(() => {
|
||||
let conflicts = this.getConflictsOrEmpty(document, Array.from(cacheItem!.origins));
|
||||
const conflicts = this.getConflictsOrEmpty(document, Array.from(cacheItem!.origins));
|
||||
|
||||
if (this.cache) {
|
||||
this.cache.delete(key!);
|
||||
|
@ -82,7 +82,7 @@ export default class DocumentMergeConflictTracker implements vscode.Disposable,
|
|||
return false;
|
||||
}
|
||||
|
||||
let key = this.getCacheKey(document);
|
||||
const key = this.getCacheKey(document);
|
||||
if (!key) {
|
||||
return false;
|
||||
}
|
||||
|
@ -100,7 +100,7 @@ export default class DocumentMergeConflictTracker implements vscode.Disposable,
|
|||
}
|
||||
|
||||
forget(document: vscode.TextDocument) {
|
||||
let key = this.getCacheKey(document);
|
||||
const key = this.getCacheKey(document);
|
||||
|
||||
if (key) {
|
||||
this.cache.delete(key);
|
||||
|
|
|
@ -67,7 +67,7 @@ export class MergeConflictParser {
|
|||
|
||||
// Create a full descriptor from the lines that we matched. This can return
|
||||
// null if the descriptor could not be completed.
|
||||
let completeDescriptor = MergeConflictParser.scanItemTolMergeConflictDescriptor(document, currentConflict);
|
||||
const completeDescriptor = MergeConflictParser.scanItemTolMergeConflictDescriptor(document, currentConflict);
|
||||
|
||||
if (completeDescriptor !== null) {
|
||||
conflictDescriptors.push(completeDescriptor);
|
||||
|
@ -90,7 +90,7 @@ export class MergeConflictParser {
|
|||
return null;
|
||||
}
|
||||
|
||||
let tokenAfterCurrentBlock: vscode.TextLine = scanned.commonAncestors[0] || scanned.splitter;
|
||||
const tokenAfterCurrentBlock: vscode.TextLine = scanned.commonAncestors[0] || scanned.splitter;
|
||||
|
||||
// Assume that descriptor.current.header, descriptor.incoming.header and descriptor.splitter
|
||||
// have valid ranges, fill in content and total ranges from these parts.
|
||||
|
@ -110,7 +110,7 @@ export class MergeConflictParser {
|
|||
name: scanned.startHeader.text.substring(startHeaderMarker.length + 1)
|
||||
},
|
||||
commonAncestors: scanned.commonAncestors.map((currentTokenLine, index, commonAncestors) => {
|
||||
let nextTokenLine = commonAncestors[index + 1] || scanned.splitter;
|
||||
const nextTokenLine = commonAncestors[index + 1] || scanned.splitter;
|
||||
return {
|
||||
header: currentTokenLine.range,
|
||||
decoratorContent: new vscode.Range(
|
||||
|
@ -146,7 +146,7 @@ export class MergeConflictParser {
|
|||
return false;
|
||||
}
|
||||
|
||||
let text = document.getText();
|
||||
const text = document.getText();
|
||||
return text.includes(startHeaderMarker) && text.includes(endFooterMarker);
|
||||
}
|
||||
|
||||
|
|
|
@ -137,7 +137,7 @@ export default class MergeDecorator implements vscode.Disposable {
|
|||
|
||||
private generateBlockRenderOptions(backgroundColor: string, overviewRulerColor: string, config: interfaces.IExtensionConfiguration): vscode.DecorationRenderOptions {
|
||||
|
||||
let renderOptions: vscode.DecorationRenderOptions = {};
|
||||
const renderOptions: vscode.DecorationRenderOptions = {};
|
||||
|
||||
if (config.enableDecorations) {
|
||||
renderOptions.backgroundColor = new vscode.ThemeColor(backgroundColor);
|
||||
|
@ -176,7 +176,7 @@ export default class MergeDecorator implements vscode.Disposable {
|
|||
try {
|
||||
this.updating.set(editor, true);
|
||||
|
||||
let conflicts = await this.tracker.getConflicts(editor.document);
|
||||
const conflicts = await this.tracker.getConflicts(editor.document);
|
||||
if (vscode.window.visibleTextEditors.indexOf(editor) === -1) {
|
||||
return;
|
||||
}
|
||||
|
@ -188,9 +188,9 @@ export default class MergeDecorator implements vscode.Disposable {
|
|||
|
||||
// Store decorations keyed by the type of decoration, set decoration wants a "style"
|
||||
// to go with it, which will match this key (see constructor);
|
||||
let matchDecorations: { [key: string]: vscode.Range[] } = {};
|
||||
const matchDecorations: { [key: string]: vscode.Range[] } = {};
|
||||
|
||||
let pushDecoration = (key: string, d: vscode.Range) => {
|
||||
const pushDecoration = (key: string, d: vscode.Range) => {
|
||||
matchDecorations[key] = matchDecorations[key] || [];
|
||||
matchDecorations[key].push(d);
|
||||
};
|
||||
|
@ -224,7 +224,7 @@ export default class MergeDecorator implements vscode.Disposable {
|
|||
// For each match we've generated, apply the generated decoration with the matching decoration type to the
|
||||
// editor instance. Keys in both matches and decorations should match.
|
||||
Object.keys(matchDecorations).forEach(decorationKey => {
|
||||
let decorationType = this.decorations[decorationKey];
|
||||
const decorationType = this.decorations[decorationKey];
|
||||
|
||||
if (decorationType) {
|
||||
editor.setDecorations(decorationType, matchDecorations[decorationKey]);
|
||||
|
@ -242,7 +242,7 @@ export default class MergeDecorator implements vscode.Disposable {
|
|||
|
||||
// Race condition, while editing the settings, it's possible to
|
||||
// generate regions before the configuration has been refreshed
|
||||
let decorationType = this.decorations[decorationKey];
|
||||
const decorationType = this.decorations[decorationKey];
|
||||
|
||||
if (decorationType) {
|
||||
editor.setDecorations(decorationType, []);
|
||||
|
|
|
@ -21,7 +21,7 @@ export default class ServiceWrapper implements vscode.Disposable {
|
|||
|
||||
begin() {
|
||||
|
||||
let configuration = this.createExtensionConfiguration();
|
||||
const configuration = this.createExtensionConfiguration();
|
||||
const documentTracker = new DocumentTracker();
|
||||
|
||||
this.services.push(
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue