Merge commit 'be3e8236086165e5e45a5a10783823874b3f3ebd' as 'lib/vscode'
This commit is contained in:
204
lib/vscode/extensions/npm/src/features/bowerJSONContribution.ts
Normal file
204
lib/vscode/extensions/npm/src/features/bowerJSONContribution.ts
Normal file
@@ -0,0 +1,204 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { MarkdownString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace } from 'vscode';
|
||||
import { IJSONContribution, ISuggestionsCollector } from './jsonContributions';
|
||||
import { XHRRequest } from 'request-light';
|
||||
import { Location } from 'jsonc-parser';
|
||||
|
||||
import * as nls from 'vscode-nls';
|
||||
const localize = nls.loadMessageBundle();
|
||||
|
||||
const USER_AGENT = 'Visual Studio Code';
|
||||
|
||||
export class BowerJSONContribution implements IJSONContribution {
|
||||
|
||||
private topRanked = ['twitter', 'bootstrap', 'angular-1.1.6', 'angular-latest', 'angulerjs', 'd3', 'myjquery', 'jq', 'abcdef1234567890', 'jQuery', 'jquery-1.11.1', 'jquery',
|
||||
'sushi-vanilla-x-data', 'font-awsome', 'Font-Awesome', 'font-awesome', 'fontawesome', 'html5-boilerplate', 'impress.js', 'homebrew',
|
||||
'backbone', 'moment1', 'momentjs', 'moment', 'linux', 'animate.css', 'animate-css', 'reveal.js', 'jquery-file-upload', 'blueimp-file-upload', 'threejs', 'express', 'chosen',
|
||||
'normalize-css', 'normalize.css', 'semantic', 'semantic-ui', 'Semantic-UI', 'modernizr', 'underscore', 'underscore1',
|
||||
'material-design-icons', 'ionic', 'chartjs', 'Chart.js', 'nnnick-chartjs', 'select2-ng', 'select2-dist', 'phantom', 'skrollr', 'scrollr', 'less.js', 'leancss', 'parser-lib',
|
||||
'hui', 'bootstrap-languages', 'async', 'gulp', 'jquery-pjax', 'coffeescript', 'hammer.js', 'ace', 'leaflet', 'jquery-mobile', 'sweetalert', 'typeahead.js', 'soup', 'typehead.js',
|
||||
'sails', 'codeigniter2'];
|
||||
|
||||
private xhr: XHRRequest;
|
||||
|
||||
public constructor(xhr: XHRRequest) {
|
||||
this.xhr = xhr;
|
||||
}
|
||||
|
||||
public getDocumentSelector(): DocumentSelector {
|
||||
return [{ language: 'json', scheme: '*', pattern: '**/bower.json' }, { language: 'json', scheme: '*', pattern: '**/.bower.json' }];
|
||||
}
|
||||
|
||||
private isEnabled() {
|
||||
return !!workspace.getConfiguration('npm').get('fetchOnlinePackageInfo');
|
||||
}
|
||||
|
||||
public collectDefaultSuggestions(_resource: string, collector: ISuggestionsCollector): Thenable<any> {
|
||||
const defaultValue = {
|
||||
'name': '${1:name}',
|
||||
'description': '${2:description}',
|
||||
'authors': ['${3:author}'],
|
||||
'version': '${4:1.0.0}',
|
||||
'main': '${5:pathToMain}',
|
||||
'dependencies': {}
|
||||
};
|
||||
const proposal = new CompletionItem(localize('json.bower.default', 'Default bower.json'));
|
||||
proposal.kind = CompletionItemKind.Class;
|
||||
proposal.insertText = new SnippetString(JSON.stringify(defaultValue, null, '\t'));
|
||||
collector.add(proposal);
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
public collectPropertySuggestions(_resource: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable<any> | null {
|
||||
if (!this.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
if ((location.matches(['dependencies']) || location.matches(['devDependencies']))) {
|
||||
if (currentWord.length > 0) {
|
||||
const queryUrl = 'https://registry.bower.io/packages/search/' + encodeURIComponent(currentWord);
|
||||
|
||||
return this.xhr({
|
||||
url: queryUrl,
|
||||
agent: USER_AGENT
|
||||
}).then((success) => {
|
||||
if (success.status === 200) {
|
||||
try {
|
||||
const obj = JSON.parse(success.responseText);
|
||||
if (Array.isArray(obj)) {
|
||||
const results = <{ name: string; description: string; }[]>obj;
|
||||
for (const result of results) {
|
||||
const name = result.name;
|
||||
const description = result.description || '';
|
||||
const insertText = new SnippetString().appendText(JSON.stringify(name));
|
||||
if (addValue) {
|
||||
insertText.appendText(': ').appendPlaceholder('latest');
|
||||
if (!isLast) {
|
||||
insertText.appendText(',');
|
||||
}
|
||||
}
|
||||
const proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = insertText;
|
||||
proposal.filterText = JSON.stringify(name);
|
||||
proposal.documentation = description;
|
||||
collector.add(proposal);
|
||||
}
|
||||
collector.setAsIncomplete();
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
} else {
|
||||
collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', success.responseText));
|
||||
return 0;
|
||||
}
|
||||
return undefined;
|
||||
}, (error) => {
|
||||
collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', error.responseText));
|
||||
return 0;
|
||||
});
|
||||
} else {
|
||||
this.topRanked.forEach((name) => {
|
||||
const insertText = new SnippetString().appendText(JSON.stringify(name));
|
||||
if (addValue) {
|
||||
insertText.appendText(': ').appendPlaceholder('latest');
|
||||
if (!isLast) {
|
||||
insertText.appendText(',');
|
||||
}
|
||||
}
|
||||
|
||||
const proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = insertText;
|
||||
proposal.filterText = JSON.stringify(name);
|
||||
proposal.documentation = '';
|
||||
collector.add(proposal);
|
||||
});
|
||||
collector.setAsIncomplete();
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public collectValueSuggestions(_resource: string, location: Location, collector: ISuggestionsCollector): Promise<any> | null {
|
||||
if (!this.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) {
|
||||
// not implemented. Could be do done calling the bower command. Waiting for web API: https://github.com/bower/registry/issues/26
|
||||
const proposal = new CompletionItem(localize('json.bower.latest.version', 'latest'));
|
||||
proposal.insertText = new SnippetString('"${1:latest}"');
|
||||
proposal.filterText = '""';
|
||||
proposal.kind = CompletionItemKind.Value;
|
||||
proposal.documentation = 'The latest version of the package';
|
||||
collector.add(proposal);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public resolveSuggestion(item: CompletionItem): Thenable<CompletionItem | null> | null {
|
||||
if (item.kind === CompletionItemKind.Property && item.documentation === '') {
|
||||
return this.getInfo(item.label).then(documentation => {
|
||||
if (documentation) {
|
||||
item.documentation = documentation;
|
||||
return item;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private getInfo(pack: string): Thenable<string | undefined> {
|
||||
const queryUrl = 'https://registry.bower.io/packages/' + encodeURIComponent(pack);
|
||||
|
||||
return this.xhr({
|
||||
url: queryUrl,
|
||||
agent: USER_AGENT
|
||||
}).then((success) => {
|
||||
try {
|
||||
const obj = JSON.parse(success.responseText);
|
||||
if (obj && obj.url) {
|
||||
let url: string = obj.url;
|
||||
if (url.indexOf('git://') === 0) {
|
||||
url = url.substring(6);
|
||||
}
|
||||
if (url.length >= 4 && url.substr(url.length - 4) === '.git') {
|
||||
url = url.substring(0, url.length - 4);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
return undefined;
|
||||
}, () => {
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
|
||||
public getInfoContribution(_resource: string, location: Location): Thenable<MarkdownString[] | null> | null {
|
||||
if (!this.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) {
|
||||
const pack = location.path[location.path.length - 1];
|
||||
if (typeof pack === 'string') {
|
||||
return this.getInfo(pack).then(documentation => {
|
||||
if (documentation) {
|
||||
const str = new MarkdownString();
|
||||
str.appendText(documentation);
|
||||
return [str];
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
172
lib/vscode/extensions/npm/src/features/jsonContributions.ts
Normal file
172
lib/vscode/extensions/npm/src/features/jsonContributions.ts
Normal file
@@ -0,0 +1,172 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { Location, getLocation, createScanner, SyntaxKind, ScanError, JSONScanner } from 'jsonc-parser';
|
||||
import { basename } from 'path';
|
||||
import { BowerJSONContribution } from './bowerJSONContribution';
|
||||
import { PackageJSONContribution } from './packageJSONContribution';
|
||||
import { XHRRequest } from 'request-light';
|
||||
|
||||
import {
|
||||
CompletionItem, CompletionItemProvider, CompletionList, TextDocument, Position, Hover, HoverProvider,
|
||||
CancellationToken, Range, MarkedString, DocumentSelector, languages, Disposable
|
||||
} from 'vscode';
|
||||
|
||||
export interface ISuggestionsCollector {
|
||||
add(suggestion: CompletionItem): void;
|
||||
error(message: string): void;
|
||||
log(message: string): void;
|
||||
setAsIncomplete(): void;
|
||||
}
|
||||
|
||||
export interface IJSONContribution {
|
||||
getDocumentSelector(): DocumentSelector;
|
||||
getInfoContribution(fileName: string, location: Location): Thenable<MarkedString[] | null> | null;
|
||||
collectPropertySuggestions(fileName: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, result: ISuggestionsCollector): Thenable<any> | null;
|
||||
collectValueSuggestions(fileName: string, location: Location, result: ISuggestionsCollector): Thenable<any> | null;
|
||||
collectDefaultSuggestions(fileName: string, result: ISuggestionsCollector): Thenable<any>;
|
||||
resolveSuggestion?(item: CompletionItem): Thenable<CompletionItem | null> | null;
|
||||
}
|
||||
|
||||
export function addJSONProviders(xhr: XHRRequest, canRunNPM: boolean): Disposable {
|
||||
const contributions = [new PackageJSONContribution(xhr, canRunNPM), new BowerJSONContribution(xhr)];
|
||||
const subscriptions: Disposable[] = [];
|
||||
contributions.forEach(contribution => {
|
||||
const selector = contribution.getDocumentSelector();
|
||||
subscriptions.push(languages.registerCompletionItemProvider(selector, new JSONCompletionItemProvider(contribution), '"', ':'));
|
||||
subscriptions.push(languages.registerHoverProvider(selector, new JSONHoverProvider(contribution)));
|
||||
});
|
||||
return Disposable.from(...subscriptions);
|
||||
}
|
||||
|
||||
export class JSONHoverProvider implements HoverProvider {
|
||||
|
||||
constructor(private jsonContribution: IJSONContribution) {
|
||||
}
|
||||
|
||||
public provideHover(document: TextDocument, position: Position, _token: CancellationToken): Thenable<Hover> | null {
|
||||
const fileName = basename(document.fileName);
|
||||
const offset = document.offsetAt(position);
|
||||
const location = getLocation(document.getText(), offset);
|
||||
if (!location.previousNode) {
|
||||
return null;
|
||||
}
|
||||
const node = location.previousNode;
|
||||
if (node && node.offset <= offset && offset <= node.offset + node.length) {
|
||||
const promise = this.jsonContribution.getInfoContribution(fileName, location);
|
||||
if (promise) {
|
||||
return promise.then(htmlContent => {
|
||||
const range = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
|
||||
const result: Hover = {
|
||||
contents: htmlContent || [],
|
||||
range: range
|
||||
};
|
||||
return result;
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export class JSONCompletionItemProvider implements CompletionItemProvider {
|
||||
|
||||
constructor(private jsonContribution: IJSONContribution) {
|
||||
}
|
||||
|
||||
public resolveCompletionItem(item: CompletionItem, _token: CancellationToken): Thenable<CompletionItem | null> {
|
||||
if (this.jsonContribution.resolveSuggestion) {
|
||||
const resolver = this.jsonContribution.resolveSuggestion(item);
|
||||
if (resolver) {
|
||||
return resolver;
|
||||
}
|
||||
}
|
||||
return Promise.resolve(item);
|
||||
}
|
||||
|
||||
public provideCompletionItems(document: TextDocument, position: Position, _token: CancellationToken): Thenable<CompletionList | null> | null {
|
||||
|
||||
const fileName = basename(document.fileName);
|
||||
|
||||
const currentWord = this.getCurrentWord(document, position);
|
||||
let overwriteRange: Range;
|
||||
|
||||
const items: CompletionItem[] = [];
|
||||
let isIncomplete = false;
|
||||
|
||||
const offset = document.offsetAt(position);
|
||||
const location = getLocation(document.getText(), offset);
|
||||
|
||||
const node = location.previousNode;
|
||||
if (node && node.offset <= offset && offset <= node.offset + node.length && (node.type === 'property' || node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
|
||||
overwriteRange = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
|
||||
} else {
|
||||
overwriteRange = new Range(document.positionAt(offset - currentWord.length), position);
|
||||
}
|
||||
|
||||
const proposed: { [key: string]: boolean } = {};
|
||||
const collector: ISuggestionsCollector = {
|
||||
add: (suggestion: CompletionItem) => {
|
||||
if (!proposed[suggestion.label]) {
|
||||
proposed[suggestion.label] = true;
|
||||
suggestion.range = { replacing: overwriteRange, inserting: new Range(overwriteRange.start, overwriteRange.start) };
|
||||
items.push(suggestion);
|
||||
}
|
||||
},
|
||||
setAsIncomplete: () => isIncomplete = true,
|
||||
error: (message: string) => console.error(message),
|
||||
log: (message: string) => console.log(message)
|
||||
};
|
||||
|
||||
let collectPromise: Thenable<any> | null = null;
|
||||
|
||||
if (location.isAtPropertyKey) {
|
||||
const scanner = createScanner(document.getText(), true);
|
||||
const addValue = !location.previousNode || !this.hasColonAfter(scanner, location.previousNode.offset + location.previousNode.length);
|
||||
const isLast = this.isLast(scanner, document.offsetAt(position));
|
||||
collectPromise = this.jsonContribution.collectPropertySuggestions(fileName, location, currentWord, addValue, isLast, collector);
|
||||
} else {
|
||||
if (location.path.length === 0) {
|
||||
collectPromise = this.jsonContribution.collectDefaultSuggestions(fileName, collector);
|
||||
} else {
|
||||
collectPromise = this.jsonContribution.collectValueSuggestions(fileName, location, collector);
|
||||
}
|
||||
}
|
||||
if (collectPromise) {
|
||||
return collectPromise.then(() => {
|
||||
if (items.length > 0) {
|
||||
return new CompletionList(items, isIncomplete);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private getCurrentWord(document: TextDocument, position: Position) {
|
||||
let i = position.character - 1;
|
||||
const text = document.lineAt(position.line).text;
|
||||
while (i >= 0 && ' \t\n\r\v":{[,'.indexOf(text.charAt(i)) === -1) {
|
||||
i--;
|
||||
}
|
||||
return text.substring(i + 1, position.character);
|
||||
}
|
||||
|
||||
private isLast(scanner: JSONScanner, offset: number): boolean {
|
||||
scanner.setPosition(offset);
|
||||
let nextToken = scanner.scan();
|
||||
if (nextToken === SyntaxKind.StringLiteral && scanner.getTokenError() === ScanError.UnexpectedEndOfString) {
|
||||
nextToken = scanner.scan();
|
||||
}
|
||||
return nextToken === SyntaxKind.CloseBraceToken || nextToken === SyntaxKind.EOF;
|
||||
}
|
||||
private hasColonAfter(scanner: JSONScanner, offset: number): boolean {
|
||||
scanner.setPosition(offset);
|
||||
return scanner.scan() === SyntaxKind.ColonToken;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const xhrDisabled = () => Promise.reject({ responseText: 'Use of online resources is disabled.' });
|
||||
@@ -0,0 +1,383 @@
|
||||
/*---------------------------------------------------------------------------------------------
|
||||
* Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
* Licensed under the MIT License. See License.txt in the project root for license information.
|
||||
*--------------------------------------------------------------------------------------------*/
|
||||
|
||||
import { MarkedString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace, MarkdownString } from 'vscode';
|
||||
import { IJSONContribution, ISuggestionsCollector } from './jsonContributions';
|
||||
import { XHRRequest } from 'request-light';
|
||||
import { Location } from 'jsonc-parser';
|
||||
|
||||
import * as cp from 'child_process';
|
||||
import * as nls from 'vscode-nls';
|
||||
const localize = nls.loadMessageBundle();
|
||||
|
||||
const LIMIT = 40;
|
||||
const SCOPED_LIMIT = 250;
|
||||
|
||||
const USER_AGENT = 'Visual Studio Code';
|
||||
|
||||
export class PackageJSONContribution implements IJSONContribution {
|
||||
|
||||
private mostDependedOn = ['lodash', 'async', 'underscore', 'request', 'commander', 'express', 'debug', 'chalk', 'colors', 'q', 'coffee-script',
|
||||
'mkdirp', 'optimist', 'through2', 'yeoman-generator', 'moment', 'bluebird', 'glob', 'gulp-util', 'minimist', 'cheerio', 'pug', 'redis', 'node-uuid',
|
||||
'socket', 'io', 'uglify-js', 'winston', 'through', 'fs-extra', 'handlebars', 'body-parser', 'rimraf', 'mime', 'semver', 'mongodb', 'jquery',
|
||||
'grunt', 'connect', 'yosay', 'underscore', 'string', 'xml2js', 'ejs', 'mongoose', 'marked', 'extend', 'mocha', 'superagent', 'js-yaml', 'xtend',
|
||||
'shelljs', 'gulp', 'yargs', 'browserify', 'minimatch', 'react', 'less', 'prompt', 'inquirer', 'ws', 'event-stream', 'inherits', 'mysql', 'esprima',
|
||||
'jsdom', 'stylus', 'when', 'readable-stream', 'aws-sdk', 'concat-stream', 'chai', 'Thenable', 'wrench'];
|
||||
|
||||
private knownScopes = ['@types', '@angular', '@babel', '@nuxtjs', '@vue', '@bazel'];
|
||||
|
||||
public getDocumentSelector(): DocumentSelector {
|
||||
return [{ language: 'json', scheme: '*', pattern: '**/package.json' }];
|
||||
}
|
||||
|
||||
public constructor(private xhr: XHRRequest, private canRunNPM: boolean) {
|
||||
}
|
||||
|
||||
public collectDefaultSuggestions(_fileName: string, result: ISuggestionsCollector): Thenable<any> {
|
||||
const defaultValue = {
|
||||
'name': '${1:name}',
|
||||
'description': '${2:description}',
|
||||
'authors': '${3:author}',
|
||||
'version': '${4:1.0.0}',
|
||||
'main': '${5:pathToMain}',
|
||||
'dependencies': {}
|
||||
};
|
||||
const proposal = new CompletionItem(localize('json.package.default', 'Default package.json'));
|
||||
proposal.kind = CompletionItemKind.Module;
|
||||
proposal.insertText = new SnippetString(JSON.stringify(defaultValue, null, '\t'));
|
||||
result.add(proposal);
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
private isEnabled() {
|
||||
return this.canRunNPM || this.onlineEnabled();
|
||||
}
|
||||
|
||||
private onlineEnabled() {
|
||||
return !!workspace.getConfiguration('npm').get('fetchOnlinePackageInfo');
|
||||
}
|
||||
|
||||
public collectPropertySuggestions(
|
||||
_resource: string,
|
||||
location: Location,
|
||||
currentWord: string,
|
||||
addValue: boolean,
|
||||
isLast: boolean,
|
||||
collector: ISuggestionsCollector
|
||||
): Thenable<any> | null {
|
||||
if (!this.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((location.matches(['dependencies']) || location.matches(['devDependencies']) || location.matches(['optionalDependencies']) || location.matches(['peerDependencies']))) {
|
||||
let queryUrl: string;
|
||||
if (currentWord.length > 0) {
|
||||
if (currentWord[0] === '@') {
|
||||
if (currentWord.indexOf('/') !== -1) {
|
||||
return this.collectScopedPackages(currentWord, addValue, isLast, collector);
|
||||
}
|
||||
for (let scope of this.knownScopes) {
|
||||
const proposal = new CompletionItem(scope);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = new SnippetString().appendText(`"${scope}/`).appendTabstop().appendText('"');
|
||||
proposal.filterText = JSON.stringify(scope);
|
||||
proposal.documentation = '';
|
||||
proposal.command = {
|
||||
title: '',
|
||||
command: 'editor.action.triggerSuggest'
|
||||
};
|
||||
collector.add(proposal);
|
||||
}
|
||||
collector.setAsIncomplete();
|
||||
}
|
||||
|
||||
queryUrl = `https://api.npms.io/v2/search/suggestions?size=${LIMIT}&q=${encodeURIComponent(currentWord)}`;
|
||||
return this.xhr({
|
||||
url: queryUrl,
|
||||
agent: USER_AGENT
|
||||
}).then((success) => {
|
||||
if (success.status === 200) {
|
||||
try {
|
||||
const obj = JSON.parse(success.responseText);
|
||||
if (obj && Array.isArray(obj)) {
|
||||
const results = <{ package: SearchPackageInfo; }[]>obj;
|
||||
for (const result of results) {
|
||||
this.processPackage(result.package, addValue, isLast, collector);
|
||||
}
|
||||
if (results.length === LIMIT) {
|
||||
collector.setAsIncomplete();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
} else {
|
||||
collector.error(localize('json.npm.error.repoaccess', 'Request to the NPM repository failed: {0}', success.responseText));
|
||||
return 0;
|
||||
}
|
||||
return undefined;
|
||||
}, (error) => {
|
||||
collector.error(localize('json.npm.error.repoaccess', 'Request to the NPM repository failed: {0}', error.responseText));
|
||||
return 0;
|
||||
});
|
||||
} else {
|
||||
this.mostDependedOn.forEach((name) => {
|
||||
const insertText = new SnippetString().appendText(JSON.stringify(name));
|
||||
if (addValue) {
|
||||
insertText.appendText(': "').appendTabstop().appendText('"');
|
||||
if (!isLast) {
|
||||
insertText.appendText(',');
|
||||
}
|
||||
}
|
||||
const proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = insertText;
|
||||
proposal.filterText = JSON.stringify(name);
|
||||
proposal.documentation = '';
|
||||
collector.add(proposal);
|
||||
});
|
||||
this.collectScopedPackages(currentWord, addValue, isLast, collector);
|
||||
collector.setAsIncomplete();
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private collectScopedPackages(currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable<any> {
|
||||
let segments = currentWord.split('/');
|
||||
if (segments.length === 2 && segments[0].length > 1) {
|
||||
let scope = segments[0].substr(1);
|
||||
let name = segments[1];
|
||||
if (name.length < 4) {
|
||||
name = '';
|
||||
}
|
||||
let queryUrl = `https://api.npms.io/v2/search?q=scope:${scope}%20${name}&size=250`;
|
||||
return this.xhr({
|
||||
url: queryUrl,
|
||||
agent: USER_AGENT
|
||||
}).then((success) => {
|
||||
if (success.status === 200) {
|
||||
try {
|
||||
const obj = JSON.parse(success.responseText);
|
||||
if (obj && Array.isArray(obj.results)) {
|
||||
const objects = <{ package: SearchPackageInfo }[]>obj.results;
|
||||
for (let object of objects) {
|
||||
this.processPackage(object.package, addValue, isLast, collector);
|
||||
}
|
||||
if (objects.length === SCOPED_LIMIT) {
|
||||
collector.setAsIncomplete();
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
} else {
|
||||
collector.error(localize('json.npm.error.repoaccess', 'Request to the NPM repository failed: {0}', success.responseText));
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
public async collectValueSuggestions(_fileName: string, location: Location, result: ISuggestionsCollector): Promise<any> {
|
||||
if (!this.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) {
|
||||
const currentKey = location.path[location.path.length - 1];
|
||||
if (typeof currentKey === 'string') {
|
||||
const info = await this.fetchPackageInfo(currentKey);
|
||||
if (info && info.version) {
|
||||
|
||||
let name = JSON.stringify(info.version);
|
||||
let proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = name;
|
||||
proposal.documentation = localize('json.npm.latestversion', 'The currently latest version of the package');
|
||||
result.add(proposal);
|
||||
|
||||
name = JSON.stringify('^' + info.version);
|
||||
proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = name;
|
||||
proposal.documentation = localize('json.npm.majorversion', 'Matches the most recent major version (1.x.x)');
|
||||
result.add(proposal);
|
||||
|
||||
name = JSON.stringify('~' + info.version);
|
||||
proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = name;
|
||||
proposal.documentation = localize('json.npm.minorversion', 'Matches the most recent minor version (1.2.x)');
|
||||
result.add(proposal);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private getDocumentation(description: string | undefined, version: string | undefined, homepage: string | undefined): MarkdownString {
|
||||
const str = new MarkdownString();
|
||||
if (description) {
|
||||
str.appendText(description);
|
||||
}
|
||||
if (version) {
|
||||
str.appendText('\n\n');
|
||||
str.appendText(localize('json.npm.version.hover', 'Latest version: {0}', version));
|
||||
}
|
||||
if (homepage) {
|
||||
str.appendText('\n\n');
|
||||
str.appendText(homepage);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
public resolveSuggestion(item: CompletionItem): Thenable<CompletionItem | null> | null {
|
||||
if (item.kind === CompletionItemKind.Property && !item.documentation) {
|
||||
return this.fetchPackageInfo(item.label).then(info => {
|
||||
if (info) {
|
||||
item.documentation = this.getDocumentation(info.description, info.version, info.homepage);
|
||||
return item;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private isValidNPMName(name: string): boolean {
|
||||
// following rules from https://github.com/npm/validate-npm-package-name
|
||||
if (!name || name.length > 214 || name.match(/^[_.]/)) {
|
||||
return false;
|
||||
}
|
||||
const match = name.match(/^(?:@([^/]+?)[/])?([^/]+?)$/);
|
||||
if (match) {
|
||||
const scope = match[1];
|
||||
if (scope && encodeURIComponent(scope) !== scope) {
|
||||
return false;
|
||||
}
|
||||
const name = match[2];
|
||||
return encodeURIComponent(name) === name;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private async fetchPackageInfo(pack: string): Promise<ViewPackageInfo | undefined> {
|
||||
if (!this.isValidNPMName(pack)) {
|
||||
return undefined; // avoid unnecessary lookups
|
||||
}
|
||||
let info: ViewPackageInfo | undefined;
|
||||
if (this.canRunNPM) {
|
||||
info = await this.npmView(pack);
|
||||
}
|
||||
if (!info && this.onlineEnabled()) {
|
||||
info = await this.npmjsView(pack);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
private npmView(pack: string): Promise<ViewPackageInfo | undefined> {
|
||||
return new Promise((resolve, _reject) => {
|
||||
const args = ['view', '--json', pack, 'description', 'dist-tags.latest', 'homepage', 'version'];
|
||||
cp.execFile(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, (error, stdout) => {
|
||||
if (!error) {
|
||||
try {
|
||||
const content = JSON.parse(stdout);
|
||||
resolve({
|
||||
description: content['description'],
|
||||
version: content['dist-tags.latest'] || content['version'],
|
||||
homepage: content['homepage']
|
||||
});
|
||||
return;
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
resolve(undefined);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private async npmjsView(pack: string): Promise<ViewPackageInfo | undefined> {
|
||||
const queryUrl = 'https://api.npms.io/v2/package/' + encodeURIComponent(pack);
|
||||
try {
|
||||
const success = await this.xhr({
|
||||
url: queryUrl,
|
||||
agent: USER_AGENT
|
||||
});
|
||||
const obj = JSON.parse(success.responseText);
|
||||
const metadata = obj?.collected?.metadata;
|
||||
if (metadata) {
|
||||
return {
|
||||
description: metadata.description || '',
|
||||
version: metadata.version,
|
||||
homepage: metadata.links?.homepage || ''
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
//ignore
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
public getInfoContribution(_fileName: string, location: Location): Thenable<MarkedString[] | null> | null {
|
||||
if (!this.isEnabled()) {
|
||||
return null;
|
||||
}
|
||||
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) {
|
||||
const pack = location.path[location.path.length - 1];
|
||||
if (typeof pack === 'string') {
|
||||
return this.fetchPackageInfo(pack).then(info => {
|
||||
if (info) {
|
||||
return [this.getDocumentation(info.description, info.version, info.homepage)];
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private processPackage(pack: SearchPackageInfo, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector) {
|
||||
if (pack && pack.name) {
|
||||
const name = pack.name;
|
||||
const insertText = new SnippetString().appendText(JSON.stringify(name));
|
||||
if (addValue) {
|
||||
insertText.appendText(': "');
|
||||
if (pack.version) {
|
||||
insertText.appendVariable('version', pack.version);
|
||||
} else {
|
||||
insertText.appendTabstop();
|
||||
}
|
||||
insertText.appendText('"');
|
||||
if (!isLast) {
|
||||
insertText.appendText(',');
|
||||
}
|
||||
}
|
||||
const proposal = new CompletionItem(name);
|
||||
proposal.kind = CompletionItemKind.Property;
|
||||
proposal.insertText = insertText;
|
||||
proposal.filterText = JSON.stringify(name);
|
||||
proposal.documentation = this.getDocumentation(pack.description, pack.version, pack?.links?.homepage);
|
||||
collector.add(proposal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface SearchPackageInfo {
|
||||
name: string;
|
||||
description?: string;
|
||||
version?: string;
|
||||
links?: { homepage?: string; };
|
||||
}
|
||||
|
||||
interface ViewPackageInfo {
|
||||
description: string;
|
||||
version?: string;
|
||||
homepage?: string;
|
||||
}
|
||||
Reference in New Issue
Block a user