Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/compiler/commandLineParser.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -841,7 +841,7 @@ namespace ts {
* @param basePath A root directory to resolve relative path entries in the config
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = []): ParsedCommandLine {
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string, resolutionStack: Path[] = [], extraFileExtensions: FileExtensionInfo[] = []): ParsedCommandLine {
const errors: Diagnostic[] = [];
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const resolvedPath = toPath(configFileName || "", basePath, getCanonicalFileName);
Expand DownExpand Up@@ -981,7 +981,7 @@ namespace ts {
includeSpecs = ["**/*"];
}

const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions);

if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
Expand DownExpand Up@@ -1185,7 +1185,7 @@ namespace ts {
* @param host The host used to resolve files and directories.
* @param errors An array for diagnostic reporting.
*/
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[]): ExpandResult {
function matchFileNames(fileNames: string[], include: string[], exclude: string[], basePath: string, options: CompilerOptions, host: ParseConfigHost, errors: Diagnostic[], extraFileExtensions: FileExtensionInfo[]): ExpandResult {
basePath = normalizePath(basePath);

// The exclude spec list is converted into a regular expression, which allows us to quickly
Expand DownExpand Up@@ -1219,7 +1219,7 @@ namespace ts {

// Rather than requery this for each file and filespec, we query the supported extensions
// once and store it on the expansion context.
const supportedExtensions = getSupportedExtensions(options);
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);

// Literal files are always included verbatim. An "include" or "exclude" specification cannot
// remove a literal file.
Expand Down
18 changes: 14 additions & 4 deletions src/compiler/core.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1924,8 +1924,18 @@ namespace ts {
export const supportedJavascriptExtensions = [".js", ".jsx"];
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);

export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]): string[] {
const needAllExtensions = options && options.allowJs;
if (!extraFileExtensions || extraFileExtensions.length === 0) {
return needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions;
}
const extensions = (needAllExtensions ? allSupportedExtensions : supportedTypeScriptExtensions).slice(0);
for (const extInfo of extraFileExtensions) {
if (needAllExtensions || extInfo.scriptKind === ScriptKind.TS) {
extensions.push(extInfo.extension);
}
}
return extensions;
}

export function hasJavaScriptFileExtension(fileName: string) {
Expand All@@ -1936,10 +1946,10 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) {
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: FileExtensionInfo[]) {
if (!fileName) { return false; }

for (const extension of getSupportedExtensions(compilerOptions)) {
for (const extension of getSupportedExtensions(compilerOptions, extraFileExtensions)) {
if (fileExtensionIs(fileName, extension)) {
return true;
}
Expand Down
6 changes: 6 additions & 0 deletions src/compiler/types.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -3086,6 +3086,12 @@ namespace ts {
ThisProperty
}

export interface FileExtensionInfo {
extension: string;
scriptKind: ScriptKind;
isMixedContent: boolean;
}

export interface DiagnosticMessage {
key: string;
category: DiagnosticCategory;
Expand Down
61 changes: 61 additions & 0 deletions src/harness/unittests/tsserverProjectSystem.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1591,6 +1591,67 @@ namespace ts.projectSystem {
checkProjectActualFiles(projectService.inferredProjects[1], [file2.path]);
});

it("tsconfig script block support", () => {
const file1 = {
path: "/a/b/f1.ts",
content: ` `
};
const file2 = {
path: "/a/b/f2.html",
content: `var hello = "hello";`
};
const config = {
path: "/a/b/tsconfig.json",
content: JSON.stringify({ compilerOptions: { allowJs: true } })
};
const host = createServerHost([file1, file2, config]);
const session = createSession(host);
openFilesForSession([file1], session);
const projectService = session.getProjectService();

// HTML file will not be included in any projects yet
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Specify .html extension as mixed content
const extraFileExtensions = [{ extension: ".html", scriptKind: ScriptKind.JS, isMixedContent: true }];
const configureHostRequest = makeSessionRequest<protocol.ConfigureRequestArguments>(CommandNames.Configure, { extraFileExtensions });
session.executeCommand(configureHostRequest).response;

// HTML file still not included in the project as it is closed
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path]);

// Open HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }],
/*changedFiles*/undefined,
/*closedFiles*/undefined);

// Now HTML file is included in the project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are available in .ts file
const project = projectService.configuredProjects[0];
let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1);
assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`);

// Close HTML file
projectService.applyChangesInOpenFiles(
/*openFiles*/undefined,
/*changedFiles*/undefined,
/*closedFiles*/[file2.path]);

// HTML file is still included in project
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(projectService.configuredProjects[0], [file1.path, file2.path]);

// Check identifiers defined in HTML content are not available in .ts file
completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 5);
assert(completions && completions.entries[0].name !== "hello", `unexpected hello entry in completion list`);
});

it("project structure update is deferred if files are not added\removed", () => {
const file1 = {
path: "/a/b/f1.ts",
Expand Down
31 changes: 24 additions & 7 deletions src/server/editorServices.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -108,6 +108,7 @@ namespace ts.server {
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
}

interface ConfigFileConversionResult {
Expand All@@ -132,13 +133,16 @@ namespace ts.server {
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T): boolean;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[]): boolean;
}

const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: _ => false
hasMixedContent: (fileName, extraFileExtensions) => {
const mixedContentExtensions = ts.map(ts.filter(extraFileExtensions, item => item.isMixedContent), item => item.extension);
return forEach(mixedContentExtensions, extension => fileExtensionIs(fileName, extension))
}
};

const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
Expand DownExpand Up@@ -282,7 +286,8 @@ namespace ts.server {

this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host"
hostInfo: "Unknown host",
extraFileExtensions: []
};

this.documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory());
Expand DownExpand Up@@ -486,7 +491,7 @@ namespace ts.server {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) {
if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}

Expand DownExpand Up@@ -642,6 +647,9 @@ namespace ts.server {
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
Expand DownExpand Up@@ -810,7 +818,9 @@ namespace ts.server {
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename);
configFilename,
/*resolutionStack*/ [],
this.hostConfiguration.extraFileExtensions);

if (parsedCommandLine.errors.length) {
errors = concatenate(errors, parsedCommandLine.errors);
Expand DownExpand Up@@ -914,7 +924,7 @@ namespace ts.server {
for (const f of files) {
const rootFilename = propertyReader.getFileName(f);
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
if (this.host.fileExists(rootFilename)) {
const info = this.getOrCreateScriptInfoForNormalizedPath(toNormalizedPath(rootFilename), /*openedByClient*/ clientFileName == rootFilename, /*fileContent*/ undefined, scriptKind, hasMixedContent);
project.addRoot(info);
Expand DownExpand Up@@ -960,7 +970,7 @@ namespace ts.server {
rootFilesChanged = true;
if (!scriptInfo) {
const scriptKind = propertyReader.getScriptKind(f);
const hasMixedContent = propertyReader.hasMixedContent(f);
const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions);
scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, /*openedByClient*/ false, /*fileContent*/ undefined, scriptKind, hasMixedContent);
}
}
Expand DownExpand Up@@ -1110,6 +1120,9 @@ namespace ts.server {
if (info) {
if (openedByClient && !info.isScriptOpen()) {
info.open(fileContent);
if (hasMixedContent) {
info.registerFileUpdate();
}
}
else if (fileContent !== undefined) {
info.reload(fileContent);
Expand DownExpand Up@@ -1144,6 +1157,10 @@ namespace ts.server {
mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions));
this.logger.info("Format host information updated");
}
if (args.extraFileExtensions) {
this.hostConfiguration.extraFileExtensions = args.extraFileExtensions;
this.logger.info("Host file extension mappings updated");
}
}
}

Expand Down
19 changes: 15 additions & 4 deletions src/server/project.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="..\services\services.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts"/>
/// <reference path="scriptInfo.ts"/>
/// <reference path="lsHost.ts"/>
Expand DownExpand Up@@ -187,6 +187,10 @@ namespace ts.server {
public languageServiceEnabled = true;

builder: Builder;
/**
* Set of files names that were updated since the last call to getChangesSinceVersion.
*/
private updatedFileNames: Map<string>;
/**
* Set of files that was returned from the last call to getChangesSinceVersion.
*/
Expand DownExpand Up@@ -480,6 +484,10 @@ namespace ts.server {
this.markAsDirty();
}

registerFileUpdate(fileName: string) {
(this.updatedFileNames || (this.updatedFileNames = createMap<string>()))[fileName] = fileName;
}

markAsDirty() {
this.projectStateVersion++;
}
Expand DownExpand Up@@ -667,10 +675,12 @@ namespace ts.server {
isInferred: this.projectKind === ProjectKind.Inferred,
options: this.getCompilerOptions()
};
const updatedFileNames = this.updatedFileNames;
this.updatedFileNames = undefined;
// check if requested version is the same that we have reported last time

@vladimaVladimir Matveev (vladima)Dec 9, 2016

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would make it more like

letupdatedFileNames=this.updatedFileNames;this.updatedFileNames=undefined;/// use local updatedFileNames - this way we'll know that set of names is definitely cleared

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - good idea

if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) {
// if current structure version is the same - return info witout any changes
if (this.projectStructureVersion == this.lastReportedVersion) {
// if current structure version is the same - return info without any changes
if (this.projectStructureVersion == this.lastReportedVersion && !updatedFileNames) {
return { info, projectErrors: this.projectErrors };
}
// compute and return the difference
Expand All@@ -679,6 +689,7 @@ namespace ts.server {

const added: string[] = [];
const removed: string[] = [];
const updated: string[] = getOwnKeys(updatedFileNames);
for (const id in currentFiles) {
if (!hasProperty(lastReportedFileNames, id)) {
added.push(id);
Expand All@@ -691,7 +702,7 @@ namespace ts.server {
}
this.lastReportedFileNames = currentFiles;
this.lastReportedVersion = this.projectStructureVersion;
return { info, changes: { added, removed }, projectErrors: this.projectErrors };
return { info, changes: { added, removed, updated }, projectErrors: this.projectErrors };
}
else {
// unknown version - return everything
Expand Down
11 changes: 10 additions & 1 deletion src/server/protocol.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/**
/**
* Declaration module describing the TypeScript Server protocol
*/
namespace ts.server.protocol {
Expand DownExpand Up@@ -918,6 +918,10 @@ namespace ts.server.protocol {
* List of removed files
*/
removed: string[];
/**
* List of updated files
*/
updated: string[];
}

/**
Expand DownExpand Up@@ -990,6 +994,11 @@ namespace ts.server.protocol {
* The format options to use during formatting and other code editing features.
*/
formatOptions?: FormatCodeSettings;

/**
* The host's additional supported file extensions
*/
extraFileExtensions?: FileExtensionInfo[];
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/server/scriptInfo.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -170,7 +170,6 @@ namespace ts.server {

private isOpen: boolean;

// TODO: allow to update hasMixedContent from the outside
constructor(
private readonly host: ServerHost,
readonly fileName: NormalizedPath,
Expand DownExpand Up@@ -268,6 +267,12 @@ namespace ts.server {
return this.containingProjects[0];
}

registerFileUpdate(): void {
for (const p of this.containingProjects) {
p.registerFileUpdate(this.path);
}
}

setFormatOptions(formatSettings: FormatCodeSettings): void {
if (formatSettings) {
if (!this.formatCodeSettings) {
Expand Down
2 changes: 1 addition & 1 deletion src/server/utilities.ts
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
/// <reference path="types.d.ts" />
/// <reference path="types.d.ts" />
/// <reference path="shared.ts" />

namespace ts.server {
Expand Down