Merge branch 'master' of https://github.com/Microsoft/TypeScript into i2531

# Conflicts:
#	src/server/session.ts
This commit is contained in:
zhengbli 2016-04-21 14:47:31 -07:00
commit 8709975f0b
2211 changed files with 85799 additions and 73321 deletions

4
.gitignore vendored
View File

@ -6,6 +6,8 @@ tests/cases/perf/*
!tests/cases/webharness/compilerToString.js
test-args.txt
~*.docx
\#*\#
.\#*
tests/baselines/local/*
tests/services/baselines/local/*
tests/baselines/prototyping/local/*
@ -26,6 +28,8 @@ rwc-report.html
*.swp
build.json
*.actual
tests/webTestServer.js
tests/webTestServer.js.map
tests/webhost/*.d.ts
tests/webhost/webtsc.js
tests/cases/**/*.js

View File

@ -150,7 +150,10 @@ var harnessSources = harnessCoreSources.concat([
"reuseProgramStructure.ts",
"cachingInServerLSHost.ts",
"moduleResolution.ts",
"tsconfigParsing.ts"
"tsconfigParsing.ts",
"commandLineParsing.ts",
"convertCompilerOptionsFromJson.ts",
"convertTypingOptionsFromJson.ts"
].map(function (f) {
return path.join(unittestsDirectory, f);
})).concat([
@ -162,18 +165,47 @@ var harnessSources = harnessCoreSources.concat([
return path.join(serverDirectory, f);
}));
var librarySourceMap = [
{ target: "lib.core.d.ts", sources: ["header.d.ts", "core.d.ts"] },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], },
{ target: "lib.d.ts", sources: ["header.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.core.es6.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts"]},
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"]},
{ target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
var es2015LibrarySources = [
"es2015.core.d.ts",
"es2015.collection.d.ts",
"es2015.generator.d.ts",
"es2015.iterable.d.ts",
"es2015.promise.d.ts",
"es2015.proxy.d.ts",
"es2015.reflect.d.ts",
"es2015.symbol.d.ts",
"es2015.symbol.wellknown.d.ts",
];
var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
var es2016LibrarySource = [ "es2016.array.include.d.ts" ];
var es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
})
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]
var librarySourceMap = [
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"], },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"], },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
{ target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] },
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources), },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources, "dom.iterable.d.ts"), },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap);
var libraryTargets = librarySourceMap.map(function (f) {
return path.join(builtLocalDirectory, f.target);
});
@ -212,7 +244,7 @@ function concatenateFiles(destinationFile, sourceFiles) {
}
var useDebugMode = true;
var host = (process.env.host || process.env.TYPESCRIPT_HOST || "node");
var host = (process.env.TYPESCRIPT_HOST || process.env.host || "node");
var compilerFilename = "tsc.js";
var LKGCompiler = path.join(LKGDirectory, compilerFilename);
var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
@ -652,7 +684,7 @@ function deleteTemporaryProjectOutput() {
}
}
function runConsoleTests(defaultReporter, defaultSubsets, postLint) {
function runConsoleTests(defaultReporter, defaultSubsets) {
cleanTestDirs();
var debug = process.env.debug || process.env.d;
tests = process.env.test || process.env.tests || process.env.t;
@ -685,13 +717,13 @@ function runConsoleTests(defaultReporter, defaultSubsets, postLint) {
subsetRegexes = subsets.map(function (sub) { return "^" + sub + ".*$"; });
subsetRegexes.push("^(?!" + subsets.join("|") + ").*$");
}
subsetRegexes.forEach(function (subsetRegex) {
subsetRegexes.forEach(function (subsetRegex, i) {
tests = subsetRegex ? ' -g "' + subsetRegex + '"' : '';
var cmd = "mocha" + (debug ? " --debug-brk" : "") + " -R " + reporter + tests + colors + ' -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd, function () {
deleteTemporaryProjectOutput();
if (postLint) {
if (i === 0) {
var lint = jake.Task['lint'];
lint.addListener('complete', function () {
complete();
@ -713,7 +745,7 @@ task("runtests-parallel", ["build-rules", "tests", builtLocalDirectory], functio
desc("Runs the tests using the built run.js file. Optional arguments are: t[ests]=regex r[eporter]=[list|spec|json|<more>] d[ebug]=true color[s]=false.");
task("runtests", ["build-rules", "tests", builtLocalDirectory], function() {
runConsoleTests('mocha-fivemat-progress-reporter', [], /*postLint*/ true);
runConsoleTests('mocha-fivemat-progress-reporter', []);
}, {async: true});
desc("Generates code coverage data via instanbul");
@ -871,7 +903,6 @@ task("update-sublime", ["local", serverFile], function() {
var tslintRuleDir = "scripts/tslint";
var tslintRules = ([
"nextLineRule",
"noNullRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule",
@ -927,6 +958,7 @@ var servicesLintTargets = [
"patternMatcher.ts",
"services.ts",
"shims.ts",
"jsTyping.ts"
].map(function (s) {
return path.join(servicesDirectory, s);
});

5255
lib/lib.core.es6.d.ts vendored

File diff suppressed because it is too large Load Diff

5344
lib/lib.core.es7.d.ts vendored

File diff suppressed because it is too large Load Diff

6997
lib/lib.d.ts vendored

File diff suppressed because it is too large Load Diff

7143
lib/lib.dom.d.ts vendored

File diff suppressed because it is too large Load Diff

29
lib/lib.dom.iterable.d.ts vendored Normal file
View File

@ -0,0 +1,29 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.dom.generated.d.ts" />
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}
interface NodeList {
[Symbol.iterator](): IterableIterator<Node>
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>
}

86
lib/lib.es2015.collection.d.ts vendored Normal file
View File

@ -0,0 +1,86 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;

499
lib/lib.es2015.core.d.ts vendored Normal file
View File

@ -0,0 +1,499 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
big(): string;
/** Returns a <blink> HTML element */
blink(): string;
/** Returns a <b> HTML element */
bold(): string;
/** Returns a <tt> HTML element */
fixed(): string
/** Returns a <font> HTML element and sets the color attribute value */
fontcolor(color: string): string
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an <i> HTML element */
italics(): string;
/** Returns an <a> HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a <small> HTML element */
small(): string;
/** Returns a <strike> HTML element */
strike(): string;
/** Returns a <sub> HTML element */
sub(): string;
/** Returns a <sup> HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}

26
lib/lib.es2015.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />

28
lib/lib.es2015.generator.d.ts vendored Normal file
View File

@ -0,0 +1,28 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;

389
lib/lib.es2015.iterable.d.ts vendored Normal file
View File

@ -0,0 +1,389 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface IteratorResult<T> {
done: boolean;
value?: T;
}
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface IterableIterator<T> extends Iterator<T> { }
interface Array<T> {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
interface Map<K, V> {
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
}
interface MapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
}
interface WeakMap<K, V> { }
interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Promise<T> { }
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}

97
lib/lib.es2015.promise.d.ts vendored Normal file
View File

@ -0,0 +1,97 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject(reason: any): Promise<void>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;

38
lib/lib.es2015.proxy.d.ts vendored Normal file
View File

@ -0,0 +1,38 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
deleteProperty? (target: T, p: PropertyKey): boolean;
defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;

32
lib/lib.es2015.reflect.d.ts vendored Normal file
View File

@ -0,0 +1,32 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}

52
lib/lib.es2015.symbol.d.ts vendored Normal file
View File

@ -0,0 +1,52 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string|number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;

372
lib/lib.es2015.symbol.wellknown.d.ts vendored Normal file
View File

@ -0,0 +1,372 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
interface Symbol {
readonly [Symbol.toStringTag]: "Symbol";
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
[Symbol.unscopables](): {
copyWithin: boolean;
entries: boolean;
fill: boolean;
find: boolean;
findIndex: boolean;
keys: boolean;
values: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
interface Promise<T> {
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
readonly [Symbol.species]: Function;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
[Symbol.species](): RegExpConstructor;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
readonly [Symbol.toStringTag]: "DataView";
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}

105
lib/lib.es2016.array.include.d.ts vendored Normal file
View File

@ -0,0 +1,105 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}

18
lib/lib.es2016.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />

View File

@ -231,14 +231,16 @@ interface Function {
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(thisArg: any, argArray?: any): any;
apply<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U;
apply(this: Function, thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(thisArg: any, ...argArray: any[]): any;
call<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): U;
call(this: Function, thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body as the original function.
@ -246,7 +248,8 @@ interface Function {
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;
bind<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): (this: void, ...argArray: any[]) => U;
bind(this: Function, thisArg: any, ...argArray: any[]): any;
prototype: any;
readonly length: number;
@ -320,13 +323,13 @@ interface String {
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
match(regexp: string): RegExpMatchArray;
match(regexp: string): RegExpMatchArray | null;
/**
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
*/
match(regexp: RegExp): RegExpMatchArray;
match(regexp: RegExp): RegExpMatchArray | null;
/**
* Replaces text in a string, using a regular expression or search string.
@ -829,7 +832,7 @@ interface RegExp {
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/
exec(string: string): RegExpExecArray;
exec(string: string): RegExpExecArray | null;
/**
* Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
@ -852,7 +855,7 @@ interface RegExp {
lastIndex: number;
// Non-standard extensions
compile(): RegExp;
compile(): this;
}
interface RegExpConstructor {
@ -1124,7 +1127,7 @@ interface Array<T> {
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
pop(): T | undefined;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
@ -1142,7 +1145,7 @@ interface Array<T> {
/**
* Removes the first element from an array and returns it.
*/
shift(): T;
shift(): T | undefined;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
@ -1535,7 +1538,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -1546,7 +1549,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -1808,7 +1811,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -1819,7 +1822,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2082,7 +2085,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2093,7 +2096,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2355,7 +2358,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2366,7 +2369,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2629,7 +2632,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2640,7 +2643,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2902,7 +2905,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2913,7 +2916,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3175,7 +3178,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3186,7 +3189,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3448,7 +3451,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3459,7 +3462,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3722,7 +3725,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3733,7 +3736,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3920,3 +3923,204 @@ interface Float64ArrayConstructor {
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
declare const Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}

9783
lib/lib.es6.d.ts vendored

File diff suppressed because it is too large Load Diff

18829
lib/lib.es7.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference path="lib.core.d.ts" />
/// <reference no-default-lib="true"/>
/////////////////////////////

733
lib/lib.webworker.d.ts vendored

File diff suppressed because it is too large Load Diff

8054
lib/tsc.js

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

390
lib/typescript.d.ts vendored
View File

@ -167,163 +167,166 @@ declare namespace ts {
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
FromKeyword = 134,
GlobalKeyword = 135,
OfKeyword = 136,
QualifiedName = 137,
ComputedPropertyName = 138,
TypeParameter = 139,
Parameter = 140,
Decorator = 141,
PropertySignature = 142,
PropertyDeclaration = 143,
MethodSignature = 144,
MethodDeclaration = 145,
Constructor = 146,
GetAccessor = 147,
SetAccessor = 148,
CallSignature = 149,
ConstructSignature = 150,
IndexSignature = 151,
TypePredicate = 152,
TypeReference = 153,
FunctionType = 154,
ConstructorType = 155,
TypeQuery = 156,
TypeLiteral = 157,
ArrayType = 158,
TupleType = 159,
UnionType = 160,
IntersectionType = 161,
ParenthesizedType = 162,
ThisType = 163,
StringLiteralType = 164,
ObjectBindingPattern = 165,
ArrayBindingPattern = 166,
BindingElement = 167,
ArrayLiteralExpression = 168,
ObjectLiteralExpression = 169,
PropertyAccessExpression = 170,
ElementAccessExpression = 171,
CallExpression = 172,
NewExpression = 173,
TaggedTemplateExpression = 174,
TypeAssertionExpression = 175,
ParenthesizedExpression = 176,
FunctionExpression = 177,
ArrowFunction = 178,
DeleteExpression = 179,
TypeOfExpression = 180,
VoidExpression = 181,
AwaitExpression = 182,
PrefixUnaryExpression = 183,
PostfixUnaryExpression = 184,
BinaryExpression = 185,
ConditionalExpression = 186,
TemplateExpression = 187,
YieldExpression = 188,
SpreadElementExpression = 189,
ClassExpression = 190,
OmittedExpression = 191,
ExpressionWithTypeArguments = 192,
AsExpression = 193,
TemplateSpan = 194,
SemicolonClassElement = 195,
Block = 196,
VariableStatement = 197,
EmptyStatement = 198,
ExpressionStatement = 199,
IfStatement = 200,
DoStatement = 201,
WhileStatement = 202,
ForStatement = 203,
ForInStatement = 204,
ForOfStatement = 205,
ContinueStatement = 206,
BreakStatement = 207,
ReturnStatement = 208,
WithStatement = 209,
SwitchStatement = 210,
LabeledStatement = 211,
ThrowStatement = 212,
TryStatement = 213,
DebuggerStatement = 214,
VariableDeclaration = 215,
VariableDeclarationList = 216,
FunctionDeclaration = 217,
ClassDeclaration = 218,
InterfaceDeclaration = 219,
TypeAliasDeclaration = 220,
EnumDeclaration = 221,
ModuleDeclaration = 222,
ModuleBlock = 223,
CaseBlock = 224,
ImportEqualsDeclaration = 225,
ImportDeclaration = 226,
ImportClause = 227,
NamespaceImport = 228,
NamedImports = 229,
ImportSpecifier = 230,
ExportAssignment = 231,
ExportDeclaration = 232,
NamedExports = 233,
ExportSpecifier = 234,
MissingDeclaration = 235,
ExternalModuleReference = 236,
JsxElement = 237,
JsxSelfClosingElement = 238,
JsxOpeningElement = 239,
JsxText = 240,
JsxClosingElement = 241,
JsxAttribute = 242,
JsxSpreadAttribute = 243,
JsxExpression = 244,
CaseClause = 245,
DefaultClause = 246,
HeritageClause = 247,
CatchClause = 248,
PropertyAssignment = 249,
ShorthandPropertyAssignment = 250,
EnumMember = 251,
SourceFile = 252,
JSDocTypeExpression = 253,
JSDocAllType = 254,
JSDocUnknownType = 255,
JSDocArrayType = 256,
JSDocUnionType = 257,
JSDocTupleType = 258,
JSDocNullableType = 259,
JSDocNonNullableType = 260,
JSDocRecordType = 261,
JSDocRecordMember = 262,
JSDocTypeReference = 263,
JSDocOptionalType = 264,
JSDocFunctionType = 265,
JSDocVariadicType = 266,
JSDocConstructorType = 267,
JSDocThisType = 268,
JSDocComment = 269,
JSDocTag = 270,
JSDocParameterTag = 271,
JSDocReturnTag = 272,
JSDocTypeTag = 273,
JSDocTemplateTag = 274,
SyntaxList = 275,
Count = 276,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 136,
LastKeyword = 137,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 152,
LastTypeNode = 164,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 136,
LastToken = 137,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@ -332,7 +335,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 137,
FirstNode = 138,
}
enum NodeFlags {
None = 0,
@ -366,12 +369,13 @@ declare namespace ts {
JavaScriptFile = 134217728,
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
AccessibilityModifier = 28,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
ContextFlags = 62914560,
ContextFlags = 197132288,
TypeExcludesFlags = 41943040,
}
enum JsxFlags {
@ -401,6 +405,9 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@ -702,6 +709,7 @@ declare namespace ts {
dotToken: Node;
name: Identifier;
}
type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
@ -731,6 +739,9 @@ declare namespace ts {
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
@ -854,6 +865,7 @@ declare namespace ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@ -923,6 +935,10 @@ declare namespace ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
@ -1044,6 +1060,7 @@ declare namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
/**
@ -1066,7 +1083,7 @@ declare namespace ts {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
class OperationCanceledException {
}
@ -1141,6 +1158,7 @@ declare namespace ts {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[];
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
@ -1186,7 +1204,7 @@ declare namespace ts {
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@ -1310,6 +1328,7 @@ declare namespace ts {
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
}
interface SymbolTable {
[index: string]: Symbol;
@ -1394,6 +1413,7 @@ declare namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType?: Type;
}
enum IndexKind {
String = 0,
@ -1442,10 +1462,12 @@ declare namespace ts {
type RootPaths = string[];
type PathSubstitutions = Map<string[]>;
type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@ -1455,6 +1477,7 @@ declare namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@ -1464,6 +1487,7 @@ declare namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@ -1492,11 +1516,30 @@ declare namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
interface DiscoverTypingsInfo {
fileNames: string[];
projectRootPath: string;
safeListPath: string;
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
}
enum ModuleKind {
None = 0,
@ -1540,6 +1583,7 @@ declare namespace ts {
}
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
@ -1557,16 +1601,29 @@ declare namespace ts {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
primary: boolean;
resolvedFileName?: string;
}
interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
}
interface TextSpan {
start: number;
@ -1578,8 +1635,8 @@ declare namespace ts {
}
}
declare namespace ts {
type FileWatcherCallback = (path: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (path: string) => void;
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface System {
args: string[];
newLine: string;
@ -1587,7 +1644,7 @@ declare namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@ -1596,6 +1653,8 @@ declare namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@ -1603,7 +1662,7 @@ declare namespace ts {
close(): void;
}
interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
var sys: System;
@ -1685,17 +1744,26 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
const version: string;
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
@ -1705,7 +1773,6 @@ declare namespace ts {
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@ -1735,6 +1802,10 @@ declare namespace ts {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
}
declare namespace ts {
/** The version of the language service API */
@ -1812,6 +1883,7 @@ declare namespace ts {
}
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@ -1836,6 +1908,7 @@ declare namespace ts {
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
interface LanguageService {
@ -1880,7 +1953,6 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {

File diff suppressed because it is too large Load Diff

View File

@ -167,163 +167,166 @@ declare namespace ts {
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
FromKeyword = 134,
GlobalKeyword = 135,
OfKeyword = 136,
QualifiedName = 137,
ComputedPropertyName = 138,
TypeParameter = 139,
Parameter = 140,
Decorator = 141,
PropertySignature = 142,
PropertyDeclaration = 143,
MethodSignature = 144,
MethodDeclaration = 145,
Constructor = 146,
GetAccessor = 147,
SetAccessor = 148,
CallSignature = 149,
ConstructSignature = 150,
IndexSignature = 151,
TypePredicate = 152,
TypeReference = 153,
FunctionType = 154,
ConstructorType = 155,
TypeQuery = 156,
TypeLiteral = 157,
ArrayType = 158,
TupleType = 159,
UnionType = 160,
IntersectionType = 161,
ParenthesizedType = 162,
ThisType = 163,
StringLiteralType = 164,
ObjectBindingPattern = 165,
ArrayBindingPattern = 166,
BindingElement = 167,
ArrayLiteralExpression = 168,
ObjectLiteralExpression = 169,
PropertyAccessExpression = 170,
ElementAccessExpression = 171,
CallExpression = 172,
NewExpression = 173,
TaggedTemplateExpression = 174,
TypeAssertionExpression = 175,
ParenthesizedExpression = 176,
FunctionExpression = 177,
ArrowFunction = 178,
DeleteExpression = 179,
TypeOfExpression = 180,
VoidExpression = 181,
AwaitExpression = 182,
PrefixUnaryExpression = 183,
PostfixUnaryExpression = 184,
BinaryExpression = 185,
ConditionalExpression = 186,
TemplateExpression = 187,
YieldExpression = 188,
SpreadElementExpression = 189,
ClassExpression = 190,
OmittedExpression = 191,
ExpressionWithTypeArguments = 192,
AsExpression = 193,
TemplateSpan = 194,
SemicolonClassElement = 195,
Block = 196,
VariableStatement = 197,
EmptyStatement = 198,
ExpressionStatement = 199,
IfStatement = 200,
DoStatement = 201,
WhileStatement = 202,
ForStatement = 203,
ForInStatement = 204,
ForOfStatement = 205,
ContinueStatement = 206,
BreakStatement = 207,
ReturnStatement = 208,
WithStatement = 209,
SwitchStatement = 210,
LabeledStatement = 211,
ThrowStatement = 212,
TryStatement = 213,
DebuggerStatement = 214,
VariableDeclaration = 215,
VariableDeclarationList = 216,
FunctionDeclaration = 217,
ClassDeclaration = 218,
InterfaceDeclaration = 219,
TypeAliasDeclaration = 220,
EnumDeclaration = 221,
ModuleDeclaration = 222,
ModuleBlock = 223,
CaseBlock = 224,
ImportEqualsDeclaration = 225,
ImportDeclaration = 226,
ImportClause = 227,
NamespaceImport = 228,
NamedImports = 229,
ImportSpecifier = 230,
ExportAssignment = 231,
ExportDeclaration = 232,
NamedExports = 233,
ExportSpecifier = 234,
MissingDeclaration = 235,
ExternalModuleReference = 236,
JsxElement = 237,
JsxSelfClosingElement = 238,
JsxOpeningElement = 239,
JsxText = 240,
JsxClosingElement = 241,
JsxAttribute = 242,
JsxSpreadAttribute = 243,
JsxExpression = 244,
CaseClause = 245,
DefaultClause = 246,
HeritageClause = 247,
CatchClause = 248,
PropertyAssignment = 249,
ShorthandPropertyAssignment = 250,
EnumMember = 251,
SourceFile = 252,
JSDocTypeExpression = 253,
JSDocAllType = 254,
JSDocUnknownType = 255,
JSDocArrayType = 256,
JSDocUnionType = 257,
JSDocTupleType = 258,
JSDocNullableType = 259,
JSDocNonNullableType = 260,
JSDocRecordType = 261,
JSDocRecordMember = 262,
JSDocTypeReference = 263,
JSDocOptionalType = 264,
JSDocFunctionType = 265,
JSDocVariadicType = 266,
JSDocConstructorType = 267,
JSDocThisType = 268,
JSDocComment = 269,
JSDocTag = 270,
JSDocParameterTag = 271,
JSDocReturnTag = 272,
JSDocTypeTag = 273,
JSDocTemplateTag = 274,
SyntaxList = 275,
Count = 276,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 136,
LastKeyword = 137,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 152,
LastTypeNode = 164,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 136,
LastToken = 137,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@ -332,7 +335,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 137,
FirstNode = 138,
}
enum NodeFlags {
None = 0,
@ -366,12 +369,13 @@ declare namespace ts {
JavaScriptFile = 134217728,
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
AccessibilityModifier = 28,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
ContextFlags = 62914560,
ContextFlags = 197132288,
TypeExcludesFlags = 41943040,
}
enum JsxFlags {
@ -401,6 +405,9 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@ -702,6 +709,7 @@ declare namespace ts {
dotToken: Node;
name: Identifier;
}
type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
@ -731,6 +739,9 @@ declare namespace ts {
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
@ -854,6 +865,7 @@ declare namespace ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@ -923,6 +935,10 @@ declare namespace ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
@ -1044,6 +1060,7 @@ declare namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
/**
@ -1066,7 +1083,7 @@ declare namespace ts {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
class OperationCanceledException {
}
@ -1141,6 +1158,7 @@ declare namespace ts {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[];
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
@ -1186,7 +1204,7 @@ declare namespace ts {
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@ -1310,6 +1328,7 @@ declare namespace ts {
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
}
interface SymbolTable {
[index: string]: Symbol;
@ -1394,6 +1413,7 @@ declare namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType?: Type;
}
enum IndexKind {
String = 0,
@ -1442,10 +1462,12 @@ declare namespace ts {
type RootPaths = string[];
type PathSubstitutions = Map<string[]>;
type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@ -1455,6 +1477,7 @@ declare namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@ -1464,6 +1487,7 @@ declare namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@ -1492,11 +1516,30 @@ declare namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
interface DiscoverTypingsInfo {
fileNames: string[];
projectRootPath: string;
safeListPath: string;
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
}
enum ModuleKind {
None = 0,
@ -1540,6 +1583,7 @@ declare namespace ts {
}
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
@ -1557,16 +1601,29 @@ declare namespace ts {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
primary: boolean;
resolvedFileName?: string;
}
interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
}
interface TextSpan {
start: number;
@ -1578,8 +1635,8 @@ declare namespace ts {
}
}
declare namespace ts {
type FileWatcherCallback = (path: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (path: string) => void;
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface System {
args: string[];
newLine: string;
@ -1587,7 +1644,7 @@ declare namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@ -1596,6 +1653,8 @@ declare namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@ -1603,7 +1662,7 @@ declare namespace ts {
close(): void;
}
interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
var sys: System;
@ -1685,17 +1744,26 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
const version: string;
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
@ -1705,7 +1773,6 @@ declare namespace ts {
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@ -1735,6 +1802,10 @@ declare namespace ts {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
}
declare namespace ts {
/** The version of the language service API */
@ -1812,6 +1883,7 @@ declare namespace ts {
}
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@ -1836,6 +1908,7 @@ declare namespace ts {
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
interface LanguageService {
@ -1880,7 +1953,6 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {

File diff suppressed because it is too large Load Diff

View File

@ -76,8 +76,11 @@ module Commands {
fs.mkdirSync(directoryPath);
}
}
function normalizeSlashes(path: string): string {
return path.replace(/\\/g, "/");
}
function transalatePath(outputFolder:string, path: string): string {
return outputFolder + directorySeparator + path.replace(":", "");
return normalizeSlashes(outputFolder + directorySeparator + path.replace(":", ""));
}
function fileExists(path: string): boolean {
return fs.existsSync(path);
@ -86,7 +89,7 @@ module Commands {
var filename = transalatePath(outputFolder, f.path);
ensureDirectoriesExist(getDirectoryPath(filename));
console.log("writing filename: " + filename);
fs.writeFile(filename, f.result.contents, (err) => { });
fs.writeFileSync(filename, f.result.contents);
});
console.log("Command: tsc ");

View File

@ -1,20 +0,0 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Don't use the 'null' keyword - use 'undefined' for missing values instead";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NullWalker(sourceFile, this.getOptions()));
}
}
class NullWalker extends Lint.RuleWalker {
visitNode(node: ts.Node) {
super.visitNode(node);
if (node.kind === ts.SyntaxKind.NullKeyword) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
}
}

View File

@ -104,6 +104,7 @@ namespace ts {
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
let file: SourceFile;
let options: CompilerOptions;
let languageVersion: ScriptTarget;
let parent: Node;
let container: Node;
let blockScopeContainer: Node;
@ -122,6 +123,7 @@ namespace ts {
let hasAsyncFunctions: boolean;
let hasDecorators: boolean;
let hasParameterDecorators: boolean;
let hasJsxSpreadAttribute: boolean;
// If this file is an external module, then it is automatically in strict-mode according to
// ES6. If it is not an external module, then we'll determine if it is in strict mode or
@ -135,6 +137,7 @@ namespace ts {
function bindSourceFile(f: SourceFile, opts: CompilerOptions) {
file = f;
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = !!file.externalModuleIndicator;
classifiableNames = {};
@ -148,6 +151,7 @@ namespace ts {
file = undefined;
options = undefined;
languageVersion = undefined;
parent = undefined;
container = undefined;
blockScopeContainer = undefined;
@ -161,6 +165,7 @@ namespace ts {
hasAsyncFunctions = false;
hasDecorators = false;
hasParameterDecorators = false;
hasJsxSpreadAttribute = false;
}
return bindSourceFile;
@ -279,6 +284,7 @@ namespace ts {
Debug.assert(!hasDynamicName(node));
const isDefaultExport = node.flags & NodeFlags.Default;
// The exported symbol for an export default function/class node is always named "default"
const name = isDefaultExport && parent ? "default" : getDeclarationName(node);
@ -497,6 +503,9 @@ namespace ts {
if (hasAsyncFunctions) {
flags |= NodeFlags.HasAsyncFunctions;
}
if (hasJsxSpreadAttribute) {
flags |= NodeFlags.HasJsxSpreadAttribute;
}
}
node.flags = flags;
@ -753,6 +762,7 @@ namespace ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionType:
case SyntaxKind.JSDocFunctionType:
case SyntaxKind.ConstructorType:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
@ -900,7 +910,12 @@ namespace ts {
if (node.flags & NodeFlags.Export) {
errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
}
declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
if (isExternalModuleAugmentation(node)) {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes);
}
else {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes);
}
}
else {
const state = getModuleInstanceState(node);
@ -1113,6 +1128,35 @@ namespace ts {
}
}
function getStrictModeBlockScopeFunctionDeclarationMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getContainingClass(node)) {
return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode;
}
if (file.externalModuleIndicator) {
return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
}
return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
}
function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) {
if (languageVersion < ScriptTarget.ES6) {
// Report error if function is not top level function declaration
if (blockScopeContainer.kind !== SyntaxKind.SourceFile &&
blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration &&
!isFunctionLike(blockScopeContainer)) {
// We check first if the name is inside class declaration or class expression; if so give explicit message
// otherwise report generic error message.
const errorSpan = getErrorSpanForNode(file, node);
file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length,
getStrictModeBlockScopeFunctionDeclarationMessage(node)));
}
}
}
function checkStrictModeNumericLiteral(node: LiteralExpression) {
if (inStrictMode && node.isOctalLiteral) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
@ -1291,6 +1335,10 @@ namespace ts {
case SyntaxKind.EnumMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
case SyntaxKind.JsxSpreadAttribute:
hasJsxSpreadAttribute = true;
return;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
@ -1349,6 +1397,8 @@ namespace ts {
case SyntaxKind.ImportSpecifier:
case SyntaxKind.ExportSpecifier:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
case SyntaxKind.GlobalModuleExportDeclaration:
return bindGlobalModuleExportDeclaration(<GlobalModuleExportDeclaration>node);
case SyntaxKind.ImportClause:
return bindImportClause(<ImportClause>node);
case SyntaxKind.ExportDeclaration:
@ -1398,6 +1448,33 @@ namespace ts {
}
}
function bindGlobalModuleExportDeclaration(node: GlobalModuleExportDeclaration) {
if (node.modifiers && node.modifiers.length) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Modifiers_cannot_appear_here));
}
if (node.parent.kind !== SyntaxKind.SourceFile) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_at_top_level));
return;
}
else {
const parent = node.parent as SourceFile;
if (!isExternalModule(parent)) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_module_files));
return;
}
if (!parent.isDeclarationFile) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_declaration_files));
return;
}
}
file.symbol.globalExports = file.symbol.globalExports || {};
declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
}
function bindExportDeclaration(node: ExportDeclaration) {
if (!container.symbol || !container.symbol.exports) {
// Export * in some sort of block construct
@ -1432,7 +1509,7 @@ namespace ts {
function bindModuleExportsAssignment(node: BinaryExpression) {
// 'module.exports = expr' assignment
setCommonJsModuleIndicator(node);
bindExportAssignment(node);
declareSymbol(file.symbol.exports, file.symbol, node, SymbolFlags.Property | SymbolFlags.Export | SymbolFlags.ValueModule, SymbolFlags.None);
}
function bindThisPropertyAssignment(node: BinaryExpression) {
@ -1595,7 +1672,13 @@ namespace ts {
}
checkStrictModeFunctionName(<FunctionDeclaration>node);
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
if (inStrictMode) {
checkStrictModeFunctionDeclaration(node);
return bindBlockScopedDeclaration(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
else {
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
}
function bindFunctionExpression(node: FunctionExpression) {

File diff suppressed because it is too large Load Diff

View File

@ -58,12 +58,11 @@ namespace ts {
},
paramType: Diagnostics.KIND,
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
error: Diagnostics.Argument_for_jsx_must_be_preserve_or_react
},
{
name: "reactNamespace",
type: "string",
description: Diagnostics.Specifies_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
description: Diagnostics.Specify_the_object_invoked_for_createElement_and_spread_when_targeting_react_JSX_emit
},
{
name: "listFiles",
@ -77,7 +76,7 @@ namespace ts {
name: "mapRoot",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
description: Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
paramType: Diagnostics.LOCATION,
},
{
@ -94,7 +93,6 @@ namespace ts {
},
description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015,
paramType: Diagnostics.KIND,
error: Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_umd_es2015_or_none
},
{
name: "newLine",
@ -102,9 +100,8 @@ namespace ts {
"crlf": NewLineKind.CarriageReturnLineFeed,
"lf": NewLineKind.LineFeed
},
description: Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
description: Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
paramType: Diagnostics.NEWLINE,
error: Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF
},
{
name: "noEmit",
@ -125,6 +122,11 @@ namespace ts {
type: "boolean",
description: Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
},
{
name: "noImplicitThis",
type: "boolean",
description: Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
},
{
name: "noLib",
type: "boolean",
@ -165,7 +167,6 @@ namespace ts {
},
{
name: "pretty",
paramType: Diagnostics.KIND,
description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental,
type: "boolean"
},
@ -186,8 +187,8 @@ namespace ts {
name: "rootDir",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
paramType: Diagnostics.LOCATION,
description: Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
},
{
name: "isolatedModules",
@ -202,7 +203,7 @@ namespace ts {
name: "sourceRoot",
type: "string",
isFilePath: true,
description: Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
description: Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
paramType: Diagnostics.LOCATION,
},
{
@ -231,9 +232,8 @@ namespace ts {
"es6": ScriptTarget.ES6,
"es2015": ScriptTarget.ES2015,
},
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015_experimental,
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015,
paramType: Diagnostics.VERSION,
error: Diagnostics.Argument_for_target_option_must_be_ES3_ES5_or_ES2015
},
{
name: "version",
@ -264,8 +264,7 @@ namespace ts {
"node": ModuleResolutionKind.NodeJs,
"classic": ModuleResolutionKind.Classic,
},
description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
error: Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic,
description: Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
},
{
name: "allowUnusedLabels",
@ -309,14 +308,41 @@ namespace ts {
// this option can only be specified in tsconfig.json
// use type = object to copy the value as-is
name: "rootDirs",
type: "object",
type: "list",
isTSConfigOnly: true,
isFilePath: true
element: {
name: "rootDirs",
type: "string",
isFilePath: true
}
},
{
name: "traceModuleResolution",
name: "typesSearchPaths",
type: "list",
isTSConfigOnly: true,
element: {
name: "typesSearchPaths",
type: "string",
isFilePath: true
}
},
{
name: "typesRoot",
type: "string"
},
{
name: "types",
type: "list",
element: {
name: "types",
type: "string"
},
description: Diagnostics.Type_declaration_files_to_be_included_in_compilation
},
{
name: "traceResolution",
type: "boolean",
description: Diagnostics.Enable_tracing_of_the_module_resolution_process
description: Diagnostics.Enable_tracing_of_the_name_resolution_process
},
{
name: "allowJs",
@ -332,6 +358,70 @@ namespace ts {
name: "noImplicitUseStrict",
type: "boolean",
description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
},
{
name: "listEmittedFiles",
type: "boolean"
},
{
name: "lib",
type: "list",
element: {
name: "lib",
type: {
// JavaScript only
"es5": "lib.es5.d.ts",
"es6": "lib.es2015.d.ts",
"es2015": "lib.es2015.d.ts",
"es7": "lib.es2016.d.ts",
"es2016": "lib.es2016.d.ts",
// Host only
"dom": "lib.dom.d.ts",
"webworker": "lib.webworker.d.ts",
"scripthost": "lib.scripthost.d.ts",
// ES2015 Or ESNext By-feature options
"es2015.core": "lib.es2015.core.d.ts",
"es2015.collection": "lib.es2015.collection.d.ts",
"es2015.generator": "lib.es2015.generator.d.ts",
"es2015.iterable": "lib.es2015.iterable.d.ts",
"es2015.promise": "lib.es2015.promise.d.ts",
"es2015.proxy": "lib.es2015.proxy.d.ts",
"es2015.reflect": "lib.es2015.reflect.d.ts",
"es2015.symbol": "lib.es2015.symbol.d.ts",
"es2015.symbol.wellknown": "lib.es2015.symbol.wellknown.d.ts",
"es2016.array.include": "lib.es2016.array.include.d.ts"
},
},
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
},
{
name: "strictNullChecks",
type: "boolean",
description: Diagnostics.Enable_strict_null_checks
}
];
/* @internal */
export let typingOptionDeclarations: CommandLineOption[] = [
{
name: "enableAutoDiscovery",
type: "boolean",
},
{
name: "include",
type: "list",
element: {
name: "include",
type: "string"
}
},
{
name: "exclude",
type: "list",
element: {
name: "exclude",
type: "string"
}
}
];
@ -342,6 +432,7 @@ namespace ts {
}
let optionNameMapCache: OptionNameMap;
/* @internal */
export function getOptionNameMap(): OptionNameMap {
if (optionNameMapCache) {
@ -361,6 +452,42 @@ namespace ts {
return optionNameMapCache;
}
/* @internal */
export function createCompilerDiagnosticForInvalidCustomType(opt: CommandLineOptionOfCustomType): Diagnostic {
const namesOfType: string[] = [];
forEachKey(opt.type, key => {
namesOfType.push(` '${key}'`);
});
return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType);
}
/* @internal */
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = (value || "").trim().toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
return map[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
/* @internal */
export function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] {
const values = (value || "").trim().split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
case "string":
return ts.map(values, v => v || "");
default:
return filter(map(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v, errors)), v => !!v);
}
}
/* @internal */
export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine {
const options: CompilerOptions = {};
const fileNames: string[] = [];
@ -414,17 +541,15 @@ namespace ts {
options[opt.name] = args[i] || "";
i++;
break;
case "list":
options[opt.name] = parseListTypeOption(<CommandLineOptionOfListType>opt, args[i], errors);
i++;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
let map = <Map<number>>opt.type;
let key = (args[i] || "").toLowerCase();
options[opt.name] = parseCustomTypeOption(<CommandLineOptionOfCustomType>opt, args[i], errors);
i++;
if (hasProperty(map, key)) {
options[opt.name] = map[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
}
break;
}
}
}
@ -502,7 +627,6 @@ namespace ts {
}
}
/**
* Remove the comments from a json like text.
* Comments can be single line comments (starting with # or //) or multiline comments using / * * /
@ -536,20 +660,25 @@ namespace ts {
* file to. e.g. outDir
*/
export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}, configFileName?: string): ParsedCommandLine {
const { options: optionsFromJsonConfigFile, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath, configFileName);
const errors: Diagnostic[] = [];
const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const options = extend(existingOptions, compilerOptions);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
options.configFilePath = configFileName;
const options = extend(existingOptions, optionsFromJsonConfigFile);
const fileNames = getFileNames(errors);
return {
options,
fileNames: getFileNames(),
fileNames,
typingOptions,
errors
};
function getFileNames(): string[] {
function getFileNames(errors: Diagnostic[]): string[] {
let fileNames: string[] = [];
if (hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
if (isArray(json["files"])) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
else {
@ -560,7 +689,7 @@ namespace ts {
const filesSeen: Map<boolean> = {};
let exclude: string[] = [];
if (json["exclude"] instanceof Array) {
if (isArray(json["exclude"])) {
exclude = json["exclude"];
}
else {
@ -605,20 +734,48 @@ namespace ts {
}
}
}
if (hasProperty(json, "excludes") && !hasProperty(json, "exclude")) {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
return fileNames;
}
}
export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
const options: CompilerOptions = {};
const errors: Diagnostic[] = [];
const options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
if (configFileName && getBaseFileName(configFileName) === "jsconfig.json") {
options.allowJs = true;
}
export function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions, errors: Diagnostic[] } {
const errors: Diagnostic[] = [];
const options = convertTypingOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
return { options, errors };
}
function convertCompilerOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): CompilerOptions {
const options: CompilerOptions = getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true } : {};
convertOptionsFromJson(optionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_compiler_option_0, errors);
return options;
}
function convertTypingOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions {
const options: TypingOptions = getBaseFileName(configFileName) === "jsconfig.json"
? { enableAutoDiscovery: true, include: [], exclude: [] }
: { enableAutoDiscovery: false, include: [], exclude: [] };
convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors);
return options;
}
function convertOptionsFromJson(optionDeclarations: CommandLineOption[], jsonOptions: any, basePath: string,
defaultOptions: CompilerOptions | TypingOptions, diagnosticMessage: DiagnosticMessage, errors: Diagnostic[]) {
if (!jsonOptions) {
return { options, errors };
return ;
}
const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name);
@ -626,66 +783,50 @@ namespace ts {
for (const id in jsonOptions) {
if (hasProperty(optionNameMap, id)) {
const opt = optionNameMap[id];
const optType = opt.type;
let value = jsonOptions[id];
const expectedType = typeof optType === "string" ? optType : "string";
if (typeof value === expectedType) {
if (typeof optType !== "string") {
const key = value.toLowerCase();
if (hasProperty(optType, key)) {
value = optType[key];
}
else {
errors.push(createCompilerDiagnostic((<CommandLineOptionOfCustomType>opt).error));
value = 0;
}
}
if (opt.isFilePath) {
switch (typeof value) {
case "string":
value = normalizePath(combinePaths(basePath, value));
break;
case "object":
// "object" options with 'isFilePath' = true expected to be string arrays
let paths: string[] = [];
let invalidOptionType = false;
if (!isArray(value)) {
invalidOptionType = true;
}
else {
for (const element of <any[]>value) {
if (typeof element === "string") {
paths.push(normalizePath(combinePaths(basePath, element)));
}
else {
invalidOptionType = true;
break;
}
}
}
if (invalidOptionType) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_0_should_have_array_of_strings_as_a_value, opt.name));
}
else {
value = paths;
}
break;
}
if (value === "") {
value = ".";
}
}
options[opt.name] = value;
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType));
}
defaultOptions[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, id));
errors.push(createCompilerDiagnostic(diagnosticMessage, id));
}
}
}
return { options, errors };
function convertJsonOption(opt: CommandLineOption, value: any, basePath: string, errors: Diagnostic[]): CompilerOptionsValue {
const optType = opt.type;
const expectedType = typeof optType === "string" ? optType : "string";
if (optType === "list" && isArray(value)) {
return convertJsonOptionOfListType(<CommandLineOptionOfListType>opt, value, basePath, errors);
}
else if (typeof value === expectedType) {
if (typeof optType !== "string") {
return convertJsonOptionOfCustomType(<CommandLineOptionOfCustomType>opt, value, errors);
}
else {
if (opt.isFilePath) {
value = normalizePath(combinePaths(basePath, value));
if (value === "") {
value = ".";
}
}
}
return value;
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, expectedType));
}
}
function convertJsonOptionOfCustomType(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = value.toLowerCase();
if (hasProperty(opt.type, key)) {
return opt.type[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
function convertJsonOptionOfListType(option: CommandLineOptionOfListType, values: any[], basePath: string, errors: Diagnostic[]): any[] {
return filter(map(values, v => convertJsonOption(option.element, v, basePath, errors)), v => !!v);
}
}

View File

@ -242,8 +242,14 @@ namespace ts {
const count = array.length;
if (count > 0) {
let pos = 0;
let result = arguments.length <= 2 ? array[pos] : initial;
pos++;
let result: T | U;
if (arguments.length <= 2) {
result = array[pos];
pos++;
}
else {
result = initial;
}
while (pos < count) {
result = f(<U>result, array[pos]);
pos++;
@ -260,8 +266,14 @@ namespace ts {
if (array) {
let pos = array.length - 1;
if (pos >= 0) {
let result = arguments.length <= 2 ? array[pos] : initial;
pos--;
let result: T | U;
if (arguments.length <= 2) {
result = array[pos];
pos--;
}
else {
result = initial;
}
while (pos >= 0) {
result = f(<U>result, array[pos]);
pos--;
@ -278,6 +290,14 @@ namespace ts {
return hasOwnProperty.call(map, key);
}
export function getKeys<T>(map: Map<T>): string[] {
const keys: string[] = [];
for (const key in map) {
keys.push(key);
}
return keys;
}
export function getProperty<T>(map: Map<T>, key: string): T {
return hasOwnProperty.call(map, key) ? map[key] : undefined;
}
@ -778,6 +798,32 @@ namespace ts {
return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension;
}
export function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind {
// Using scriptKind as a condition handles both:
// - 'scriptKind' is unspecified and thus it is `undefined`
// - 'scriptKind' is set and it is `Unknown` (0)
// If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
// to get the ScriptKind from the file name. If it cannot be resolved
// from the file name then the default 'TS' script kind is returned.
return (scriptKind || getScriptKindFromFileName(fileName)) || ScriptKind.TS;
}
export function getScriptKindFromFileName(fileName: string): ScriptKind {
const ext = fileName.substr(fileName.lastIndexOf("."));
switch (ext.toLowerCase()) {
case ".js":
return ScriptKind.JS;
case ".jsx":
return ScriptKind.JSX;
case ".ts":
return ScriptKind.TS;
case ".tsx":
return ScriptKind.TSX;
default:
return ScriptKind.Unknown;
}
}
/**
* List of supported extensions in order of file resolution precedence.
*/

View File

@ -15,7 +15,7 @@ namespace ts {
reportedDeclarationError: boolean;
moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[];
synchronousDeclarationOutput: string;
referencePathsOutput: string;
referencesOutput: string;
}
type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic;
@ -35,7 +35,7 @@ namespace ts {
forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {
function getDeclarationDiagnosticsFromFile({ declarationFilePath }: EmitFileNames, sources: SourceFile[], isBundledEmit: boolean) {
emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
@ -73,7 +73,9 @@ namespace ts {
// Contains the reference paths that needs to go in the declaration file.
// Collecting this separately because reference paths need to be first thing in the declaration file
// and we could be collecting these paths from multiple files into single one with --out option
let referencePathsOutput = "";
let referencesOutput = "";
let usedTypeDirectiveReferences: Map<string>;
// Emit references corresponding to each file
const emittedReferencedFiles: SourceFile[] = [];
@ -153,11 +155,19 @@ namespace ts {
}
});
if (usedTypeDirectiveReferences) {
for (const directive in usedTypeDirectiveReferences) {
if (hasProperty(usedTypeDirectiveReferences, directive)) {
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
}
}
}
return {
reportedDeclarationError,
moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo,
synchronousDeclarationOutput: writer.getText(),
referencePathsOutput,
referencesOutput,
};
function hasInternalAnnotation(range: CommentRange) {
@ -253,6 +263,21 @@ namespace ts {
setWriter(oldWriter);
}
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[]): void {
if (!typeReferenceDirectives) {
return;
}
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = {};
}
for (const directive of typeReferenceDirectives) {
if (!hasProperty(usedTypeDirectiveReferences, directive)) {
usedTypeDirectiveReferences[directive] = directive;
}
}
}
function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) {
// write the aliases
@ -284,6 +309,7 @@ namespace ts {
function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
function reportInaccessibleThisError() {
@ -367,6 +393,8 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.ThisType:
case SyntaxKind.StringLiteralType:
return writeTextOfNode(currentText, type);
@ -418,6 +446,7 @@ namespace ts {
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
handleSymbolAccessibilityError(visibilityResult);
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
writeEntityName(entityName);
}
@ -528,7 +557,10 @@ namespace ts {
else {
// Expression
const tempVarName = getExportDefaultTempVariableName();
write("declare var ");
if (!noDeclare) {
write("declare ");
}
write("var ");
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
@ -987,6 +1019,10 @@ namespace ts {
else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) {
write("null");
}
else {
writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError;
resolver.writeBaseConstructorTypeOfClass(<ClassLikeDeclaration>enclosingDeclaration, enclosingDeclaration, TypeFormatFlags.UseTypeOfFunction, writer);
}
function getHeritageClauseVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
@ -1341,6 +1377,7 @@ namespace ts {
function emitSignatureDeclaration(node: SignatureDeclaration) {
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
let closeParenthesizedFunctionType = false;
if (node.kind === SyntaxKind.IndexSignature) {
// Index signature can have readonly modifier
@ -1352,6 +1389,16 @@ namespace ts {
if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) {
write("new ");
}
else if (node.kind === SyntaxKind.FunctionType) {
const currentOutput = writer.getText();
// Do not generate incorrect type when function type with type parameters is type argument
// This could happen if user used space between two '<' making it error free
// e.g var x: A< <Tany>(a: Tany)=>Tany>;
if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") {
closeParenthesizedFunctionType = true;
write("(");
}
}
emitTypeParameters(node.typeParameters);
write("(");
}
@ -1385,6 +1432,9 @@ namespace ts {
write(";");
writeLine();
}
else if (closeParenthesizedFunctionType) {
write(")");
}
function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic {
let diagnosticMessage: DiagnosticMessage;
@ -1679,7 +1729,7 @@ namespace ts {
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ false);
referencePathsOutput += '/// <reference path="' + declFileName + '" />' + newLine;
referencesOutput += `/// <reference path="${declFileName}" />${newLine}`;
}
return addedBundledEmitReference;
@ -1701,7 +1751,7 @@ namespace ts {
const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
const declarationOutput = emitDeclarationResult.referencePathsOutput
const declarationOutput = emitDeclarationResult.referencesOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM);
}

View File

@ -811,6 +811,18 @@
"category": "Error",
"code": 1249
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'.": {
"category": "Error",
"code": 1250
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode.": {
"category": "Error",
"code": 1251
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode.": {
"category": "Error",
"code": 1252
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
@ -831,6 +843,18 @@
"category": "Error",
"code": 1313
},
"Global module exports may only appear in module files.": {
"category": "Error",
"code": 1314
},
"Global module exports may only appear in declaration files.": {
"category": "Error",
"code": 1315
},
"Global module exports may only appear at top level.": {
"category": "Error",
"code": 1316
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@ -1035,7 +1059,7 @@
"category": "Error",
"code": 2351
},
"Neither type '{0}' nor type '{1}' is assignable to the other.": {
"Type '{0}' cannot be converted to type '{1}'.": {
"category": "Error",
"code": 2352
},
@ -1091,6 +1115,10 @@
"category": "Error",
"code": 2365
},
"Function lacks ending return statement and return type does not include 'undefined'.": {
"category": "Error",
"code": 2366
},
"Type parameter name cannot be '{0}'": {
"category": "Error",
"code": 2368
@ -1411,6 +1439,10 @@
"category": "Error",
"code": 2453
},
"Variable '{0}' is used before being assigned.": {
"category": "Error",
"code": 2454
},
"Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'.": {
"category": "Error",
"code": 2455
@ -1707,6 +1739,10 @@
"category": "Error",
"code": 2530
},
"Object is possibly 'null' or 'undefined'.": {
"category": "Error",
"code": 2531
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@ -1783,7 +1819,7 @@
"category": "Error",
"code": 2660
},
"Cannot re-export name that is not defined in the module.": {
"Cannot export '{0}'. Only local declarations can be exported from a module.": {
"category": "Error",
"code": 2661
},
@ -1847,6 +1883,42 @@
"category": "Error",
"code": 2676
},
"A type predicate's type must be assignable to its parameter's type.": {
"category": "Error",
"code": 2677
},
"Type '{0}' is not comparable to type '{1}'.": {
"category": "Error",
"code": 2678
},
"A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'.": {
"category": "Error",
"code": 2679
},
"A 'this' parameter must be the first parameter.": {
"category": "Error",
"code": 2680
},
"A constructor cannot have a 'this' parameter.": {
"category": "Error",
"code": 2681
},
"A setter cannot have a 'this' parameter.": {
"category": "Error",
"code": 2682
},
"'this' implicitly has type 'any' because it does not have a type annotation.": {
"category": "Error",
"code": 2683
},
"The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'.": {
"category": "Error",
"code": 2684
},
"The 'this' types of each signature are incompatible.": {
"category": "Error",
"code": 2685
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@ -2127,6 +2199,11 @@
"category": "Error",
"code": 4082
},
"Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict.": {
"category": "Message",
"code": 4090
},
"The current host does not support the '{0}' option.": {
"category": "Error",
"code": 5001
@ -2215,7 +2292,14 @@
"category": "Error",
"code": 5062
},
"Substututions for pattern '{0}' should be an array.": {
"category": "Error",
"code": 5063
},
"Substitution '{0}' for pattern '{1}' has incorrect type, expected 'string', got '{2}'.": {
"category": "Error",
"code": 5064
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@ -2224,11 +2308,11 @@
"category": "Message",
"code": 6002
},
"Specifies the location where debugger should locate map files instead of generated locations.": {
"Specify the location where debugger should locate map files instead of generated locations.": {
"category": "Message",
"code": 6003
},
"Specifies the location where debugger should locate TypeScript files instead of source locations.": {
"Specify the location where debugger should locate TypeScript files instead of source locations.": {
"category": "Message",
"code": 6004
},
@ -2260,7 +2344,7 @@
"category": "Message",
"code": 6011
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)": {
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015'": {
"category": "Message",
"code": 6015
},
@ -2348,14 +2432,10 @@
"category": "Error",
"code": 6045
},
"Argument for '--module' option must be 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'none'.": {
"Argument for '{0}' option must be: {1}": {
"category": "Error",
"code": 6046
},
"Argument for '--target' option must be 'ES3', 'ES5', or 'ES2015'.": {
"category": "Error",
"code": 6047
},
"Locale must be of the form <language> or <language>-<territory>. For example '{0}' or '{1}'.": {
"category": "Error",
"code": 6048
@ -2392,7 +2472,7 @@
"category": "Message",
"code": 6056
},
"Specifies the root directory of input files. Use to control the output directory structure with --outDir.": {
"Specify the root directory of input files. Use to control the output directory structure with --outDir.": {
"category": "Message",
"code": 6058
},
@ -2400,7 +2480,7 @@
"category": "Error",
"code": 6059
},
"Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"Specify the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).": {
"category": "Message",
"code": 6060
},
@ -2408,14 +2488,6 @@
"category": "Message",
"code": 6061
},
"Argument for '--newLine' option must be 'CRLF' or 'LF'.": {
"category": "Error",
"code": 6062
},
"Argument for '--moduleResolution' option must be 'node' or 'classic'.": {
"category": "Error",
"code": 6063
},
"Option '{0}' can only be specified in 'tsconfig.json' file.": {
"category": "Error",
"code": 6064
@ -2432,7 +2504,7 @@
"category": "Message",
"code": 6068
},
"Specifies module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"category": "Message",
"code": 6069
},
@ -2472,14 +2544,14 @@
"category": "Message",
"code": 6078
},
"Specify library files to be included in the compilation: ": {
"category": "Message",
"code": 6079
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
},
"Argument for '--jsx' must be 'preserve' or 'react'.": {
"category": "Message",
"code": 6081
},
"Only 'amd' and 'system' modules are supported alongside --{0}.": {
"category": "Error",
"code": 6082
@ -2488,11 +2560,11 @@
"category": "Message",
"code": 6083
},
"Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit": {
"Specify the object invoked for createElement and __spread when targeting 'react' JSX emit": {
"category": "Message",
"code": 6084
},
"Enable tracing of the module resolution process.": {
"Enable tracing of the name resolution process.": {
"category": "Message",
"code": 6085
},
@ -2540,7 +2612,7 @@
"category": "Message",
"code": 6096
},
"File '{0}' exist - use it as a module resolution result.": {
"File '{0}' exist - use it as a name resolution result.": {
"category": "Message",
"code": 6097
},
@ -2552,11 +2624,11 @@
"category": "Message",
"code": 6099
},
"'package.json' does not have 'typings' field.": {
"'package.json' does not have 'types' field.": {
"category": "Message",
"code": 6100
},
"'package.json' has 'typings' field '{0}' that references '{1}'.": {
"'package.json' has '{0}' field '{1}' that references '{2}'.": {
"category": "Message",
"code": 6101
},
@ -2572,7 +2644,7 @@
"category": "Message",
"code": 6104
},
"Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'.": {
"Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.": {
"category": "Message",
"code": 6105
},
@ -2604,7 +2676,70 @@
"category": "Message",
"code": 6112
},
"Enable strict null checks.": {
"category": "Message",
"code": 6113
},
"Unknown option 'excludes'. Did you mean 'exclude'?": {
"category": "Error",
"code": 6114
},
"Raise error on 'this' expressions with an implied 'any' type.": {
"category": "Message",
"code": 6115
},
"======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========": {
"category": "Message",
"code": 6116
},
"Resolving using primary search paths...": {
"category": "Message",
"code": 6117
},
"Resolving from node_modules folder...": {
"category": "Message",
"code": 6118
},
"======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========": {
"category": "Message",
"code": 6119
},
"======== Type reference directive '{0}' was not resolved. ========": {
"category": "Message",
"code": 6120
},
"Resolving with primary search path '{0}'": {
"category": "Message",
"code": 6121
},
"Root directory cannot be determined, skipping primary search paths.": {
"category": "Message",
"code": 6122
},
"======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========": {
"category": "Message",
"code": 6123
},
"Type declaration files to be included in compilation.": {
"category": "Message",
"code": 6124
},
"Looking up in 'node_modules' folder, initial location '{0}'": {
"category": "Message",
"code": 6125
},
"Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder.": {
"category": "Message",
"code": 6126
},
"======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========": {
"category": "Message",
"code": 6127
},
"======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========": {
"category": "Message",
"code": 6128
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@ -2693,6 +2828,10 @@
"category": "Error",
"code": 7030
},
"Binding element '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7031
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@ -2804,5 +2943,9 @@
"'super' must be called before accessing 'this' in the constructor of a derived class.": {
"category": "Error",
"code": 17009
},
"Unknown typing option '{0}'.": {
"category": "Error",
"code": 17010
}
}

View File

@ -296,11 +296,11 @@ namespace ts {
* If loop contains block scoped binding captured in some function then loop body is converted to a function.
* Lexical bindings declared in loop initializer will be passed into the loop body function as parameters,
* however if this binding is modified inside the body - this new value should be propagated back to the original binding.
* This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body.
* This is done by declaring new variable (out parameter holder) outside of the loop for every binding that is reassigned inside the body.
* On every iteration this variable is initialized with value of corresponding binding.
* At every point where control flow leaves the loop either explicitly (break/continue) or implicitly (at the end of loop body)
* we copy the value inside the loop to the out parameter holder.
*
*
* for (let x;;) {
* let a = 1;
* let b = () => a;
@ -308,9 +308,9 @@ namespace ts {
* if (...) break;
* ...
* }
*
*
* will be converted to
*
*
* var out_x;
* var loop = function(x) {
* var a = 1;
@ -326,7 +326,7 @@ namespace ts {
* x = out_x;
* if (state === "break") break;
* }
*
*
* NOTE: values to out parameters are not copies if loop is abrupted with 'return' - in this case this will end the entire enclosing function
* so nobody can observe this new value.
*/
@ -345,6 +345,16 @@ var __extends = (this && this.__extends) || function (d, b) {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};`;
const assignHelper = `
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};`;
// emit output for the __decorate helper function
const decorateHelper = `
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
@ -380,6 +390,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
const languageVersion = getEmitScriptTarget(compilerOptions);
const modulekind = getEmitModuleKind(compilerOptions);
const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
const emittedFilesList: string[] = compilerOptions.listEmittedFiles ? [] : undefined;
const emitterDiagnostics = createDiagnosticCollection();
let emitSkipped = false;
const newLine = host.getNewLine();
@ -390,6 +401,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return {
emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList
};
@ -540,6 +552,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
let convertedLoopState: ConvertedLoopState;
let extendsEmitted: boolean;
let assignEmitted: boolean;
let decorateEmitted: boolean;
let paramEmitted: boolean;
let awaiterEmitted: boolean;
@ -604,7 +617,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write(`//# sourceMappingURL=${sourceMappingURL}`);
}
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM);
writeEmittedFiles(writer.getText(), jsFilePath, sourceMapFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM, sourceFiles);
// reset the state
sourceMap.reset();
@ -623,6 +636,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
decorateEmitted = false;
paramEmitted = false;
awaiterEmitted = false;
assignEmitted = false;
tempFlags = 0;
tempVariables = undefined;
tempParameters = undefined;
@ -748,16 +762,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
/** Write emitted output to disk */
function writeEmittedFiles(emitOutput: string, jsFilePath: string, sourceMapFilePath: string, writeByteOrderMark: boolean) {
function writeEmittedFiles(emitOutput: string, jsFilePath: string, sourceMapFilePath: string, writeByteOrderMark: boolean, sourceFiles: SourceFile[]) {
if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false);
writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles);
}
if (sourceMapDataList) {
sourceMapDataList.push(sourceMap.getSourceMapData());
}
writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark);
writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles);
}
// Create a temporary variable with a unique unused name.
@ -1259,11 +1273,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
else {
// Either emit one big object literal (no spread attribs), or
// a call to React.__spread
// a call to the __assign helper
const attrs = openingNode.attributes;
if (forEach(attrs, attr => attr.kind === SyntaxKind.JsxSpreadAttribute)) {
emitExpressionIdentifier(syntheticReactRef);
write(".__spread(");
write("__assign(");
let haveOpenedObjectLiteral = false;
for (let i = 0; i < attrs.length; i++) {
@ -1533,6 +1546,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
case SyntaxKind.JsxSpreadAttribute:
case SyntaxKind.JsxExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.PostfixUnaryExpression:
case SyntaxKind.PrefixUnaryExpression:
@ -2077,8 +2091,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function parenthesizeForAccess(expr: Expression): LeftHandSideExpression {
// When diagnosing whether the expression needs parentheses, the decision should be based
// on the innermost expression in a chain of nested type assertions.
while (expr.kind === SyntaxKind.TypeAssertionExpression || expr.kind === SyntaxKind.AsExpression) {
expr = (<AssertionExpression>expr).expression;
while (expr.kind === SyntaxKind.TypeAssertionExpression ||
expr.kind === SyntaxKind.AsExpression ||
expr.kind === SyntaxKind.NonNullExpression) {
expr = (<AssertionExpression | NonNullExpression>expr).expression;
}
// isLeftHandSideExpression is almost the correct criterion for when it is not necessary
@ -2138,6 +2154,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return container && container.kind !== SyntaxKind.SourceFile;
}
// Return true if identifier resolves to an imported identifier
function isImportedReference(node: Identifier) {
const declaration = resolver.getReferencedImportDeclaration(node);
return declaration && (declaration.kind === SyntaxKind.ImportClause || declaration.kind === SyntaxKind.ImportSpecifier);
}
function emitShorthandPropertyAssignment(node: ShorthandPropertyAssignment) {
// The name property of a short-hand property assignment is considered an expression position, so here
// we manually emit the identifier to avoid rewriting.
@ -2151,7 +2173,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// let obj = { y };
// }
// Here we need to emit obj = { y : m.y } regardless of the output target.
if (modulekind !== ModuleKind.ES6 || isNamespaceExportReference(node.name)) {
// The same rules apply for imported identifiers when targeting module formats with indirect access to
// the imported identifiers. For example, when targeting CommonJS:
//
// import {foo} from './foo';
// export const baz = { foo };
//
// Must be transformed into:
//
// const foo_1 = require('./foo');
// exports.baz = { foo: foo_1.foo };
//
if (languageVersion < ScriptTarget.ES6 || (modulekind !== ModuleKind.ES6 && isImportedReference(node.name)) || isNamespaceExportReference(node.name) ) {
// Emit identifier as an identifier
write(": ");
emit(node.name);
@ -2326,8 +2359,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
function skipParentheses(node: Expression): Expression {
while (node.kind === SyntaxKind.ParenthesizedExpression || node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression) {
node = (<ParenthesizedExpression | AssertionExpression>node).expression;
while (node.kind === SyntaxKind.ParenthesizedExpression ||
node.kind === SyntaxKind.TypeAssertionExpression ||
node.kind === SyntaxKind.AsExpression ||
node.kind === SyntaxKind.NonNullExpression) {
node = (<ParenthesizedExpression | AssertionExpression | NonNullExpression>node).expression;
}
return node;
}
@ -2501,13 +2537,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
// not the user. If we didn't want them, the emitter would not have put them
// there.
if (!nodeIsSynthesized(node) && node.parent.kind !== SyntaxKind.ArrowFunction) {
if (node.expression.kind === SyntaxKind.TypeAssertionExpression || node.expression.kind === SyntaxKind.AsExpression) {
let operand = (<TypeAssertion>node.expression).expression;
if (node.expression.kind === SyntaxKind.TypeAssertionExpression ||
node.expression.kind === SyntaxKind.AsExpression ||
node.expression.kind === SyntaxKind.NonNullExpression) {
let operand = (<TypeAssertion | NonNullExpression>node.expression).expression;
// Make sure we consider all nested cast expressions, e.g.:
// (<any><number><any>-A).x;
while (operand.kind === SyntaxKind.TypeAssertionExpression || operand.kind === SyntaxKind.AsExpression) {
operand = (<TypeAssertion>operand).expression;
while (operand.kind === SyntaxKind.TypeAssertionExpression ||
operand.kind === SyntaxKind.AsExpression ||
operand.kind === SyntaxKind.NonNullExpression) {
operand = (<TypeAssertion | NonNullExpression>operand).expression;
}
// We have an expression of the form: (<Type>SubExpr)
@ -3073,7 +3113,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
writeLine();
// end of loop body -> copy out parameter
// end of loop body -> copy out parameter
copyLoopOutParameters(convertedLoopState, CopyDirection.ToOutParameter, /*emitAsStatements*/true);
decreaseIndent();
@ -3572,7 +3612,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
else {
convertedLoopState.nonLocalJumps |= Jump.Continue;
// note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
// note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
write(`"continue";`);
}
}
@ -4201,12 +4241,31 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
function emitVariableDeclaration(node: VariableDeclaration) {
if (isBindingPattern(node.name)) {
if (languageVersion < ScriptTarget.ES6) {
emitDestructuring(node, /*isAssignmentExpressionStatement*/ false);
}
else {
const isExported = getCombinedNodeFlags(node) & NodeFlags.Export;
if (languageVersion >= ScriptTarget.ES6 && (!isExported || modulekind === ModuleKind.ES6)) {
// emit ES6 destructuring only if target module is ES6 or variable is not exported
// exported variables in CJS/AMD are prefixed with 'exports.' so result javascript { exports.toString } = 1; is illegal
const isTopLevelDeclarationInSystemModule =
modulekind === ModuleKind.System &&
shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/true);
if (isTopLevelDeclarationInSystemModule) {
// In System modules top level variables are hoisted
// so variable declarations with destructuring are turned into destructuring assignments.
// As a result, they will need parentheses to disambiguate object binding assignments from blocks.
write("(");
}
emit(node.name);
emitOptional(" = ", node.initializer);
if (isTopLevelDeclarationInSystemModule) {
write(")");
}
}
else {
emitDestructuring(node, /*isAssignmentExpressionStatement*/ false);
}
}
else {
@ -4428,7 +4487,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
function emitRestParameter(node: FunctionLikeDeclaration) {
if (languageVersion < ScriptTarget.ES6 && hasRestParameter(node)) {
if (languageVersion < ScriptTarget.ES6 && hasDeclaredRestParameter(node)) {
const restIndex = node.parameters.length - 1;
const restParam = node.parameters[restIndex];
@ -4563,7 +4622,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
emitEnd(node);
if (kind !== SyntaxKind.MethodDeclaration && kind !== SyntaxKind.MethodSignature) {
if (kind !== SyntaxKind.MethodDeclaration &&
kind !== SyntaxKind.MethodSignature &&
kind !== SyntaxKind.ArrowFunction) {
emitTrailingComments(node);
}
}
@ -4582,8 +4643,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write("(");
if (node) {
const parameters = node.parameters;
const omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0;
emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false);
const skipCount = node.parameters.length && (<Identifier>node.parameters[0].name).text === "this" ? 1 : 0;
const omitCount = languageVersion < ScriptTarget.ES6 && hasDeclaredRestParameter(node) ? 1 : 0;
emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false);
}
write(")");
decreaseIndent();
@ -5261,9 +5323,11 @@ const _super = (function (geti, seti) {
function emitClassLikeDeclarationForES6AndHigher(node: ClassLikeDeclaration) {
let decoratedClassAlias: string;
const thisNodeIsDecorated = nodeIsDecorated(node);
const isHoistedDeclarationInSystemModule = shouldHoistDeclarationInSystemJsModule(node);
const isDecorated = nodeIsDecorated(node);
const rewriteAsClassExpression = isDecorated || isHoistedDeclarationInSystemModule;
if (node.kind === SyntaxKind.ClassDeclaration) {
if (thisNodeIsDecorated) {
if (rewriteAsClassExpression) {
// When we emit an ES6 class that has a class decorator, we must tailor the
// emit to certain specific cases.
//
@ -5344,7 +5408,10 @@ const _super = (function (geti, seti) {
// [Example 4]
//
if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithBodyScopedClassBinding) {
// NOTE: we reuse the same rewriting logic for cases when targeting ES6 and module kind is System.
// Because of hoisting top level class declaration need to be emitted as class expressions.
// Double bind case is only required if node is decorated.
if (isDecorated && resolver.getNodeCheckFlags(node) & NodeCheckFlags.ClassWithBodyScopedClassBinding) {
decoratedClassAlias = unescapeIdentifier(makeUniqueName(node.name ? node.name.text : "default"));
decoratedClassAliases[getNodeId(node)] = decoratedClassAlias;
write(`let ${decoratedClassAlias};`);
@ -5355,7 +5422,9 @@ const _super = (function (geti, seti) {
write("export ");
}
write("let ");
if (!isHoistedDeclarationInSystemModule) {
write("let ");
}
emitDeclarationName(node);
if (decoratedClassAlias !== undefined) {
write(` = ${decoratedClassAlias}`);
@ -5399,7 +5468,7 @@ const _super = (function (geti, seti) {
// emit name if
// - node has a name
// - this is default export with static initializers
if (node.name || (node.flags & NodeFlags.Default && (staticProperties.length > 0 || modulekind !== ModuleKind.ES6) && !thisNodeIsDecorated)) {
if (node.name || (node.flags & NodeFlags.Default && (staticProperties.length > 0 || modulekind !== ModuleKind.ES6) && !rewriteAsClassExpression)) {
write(" ");
emitDeclarationName(node);
}
@ -5419,7 +5488,7 @@ const _super = (function (geti, seti) {
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
if (thisNodeIsDecorated) {
if (rewriteAsClassExpression) {
decoratedClassAliases[getNodeId(node)] = undefined;
write(";");
}
@ -5459,7 +5528,7 @@ const _super = (function (geti, seti) {
// module), export it
if (node.flags & NodeFlags.Default) {
// if this is a top level default export of decorated class, write the export after the declaration.
if (thisNodeIsDecorated) {
if (isDecorated) {
writeLine();
write("export default ");
emitDeclarationName(node);
@ -7267,7 +7336,7 @@ const _super = (function (geti, seti) {
}
// text should be quoted string
// for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same
// for deduplication purposes in key remove leading and trailing quotes so 'a' and "a" will be considered the same
const key = text.substr(1, text.length - 2);
if (hasProperty(groupIndices, key)) {
@ -7596,7 +7665,7 @@ const _super = (function (geti, seti) {
}
function isUseStrictPrologue(node: ExpressionStatement): boolean {
return !!(node.expression as StringLiteral).text.match(/use strict/);
return (node.expression as StringLiteral).text === "use strict";
}
function ensureUseStrictPrologue(startWithNewLine: boolean, writeUseStrict: boolean) {
@ -7646,11 +7715,16 @@ const _super = (function (geti, seti) {
if (!compilerOptions.noEmitHelpers) {
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
if (languageVersion < ScriptTarget.ES6 && !extendsEmitted && node.flags & NodeFlags.HasClassExtends) {
writeLines(extendsHelper);
extendsEmitted = true;
}
if (compilerOptions.jsx !== JsxEmit.Preserve && !assignEmitted && (node.flags & NodeFlags.HasJsxSpreadAttribute)) {
writeLines(assignHelper);
assignEmitted = true;
}
if (!decorateEmitted && node.flags & NodeFlags.HasDecorators) {
writeLines(decorateHelper);
if (compilerOptions.emitDecoratorMetadata) {
@ -7805,7 +7879,7 @@ const _super = (function (geti, seti) {
node.parent &&
node.parent.kind === SyntaxKind.ArrowFunction &&
(<ArrowFunction>node.parent).body === node &&
compilerOptions.target <= ScriptTarget.ES5) {
languageVersion <= ScriptTarget.ES5) {
return false;
}
@ -7885,9 +7959,9 @@ const _super = (function (geti, seti) {
case SyntaxKind.TaggedTemplateExpression:
return emitTaggedTemplateExpression(<TaggedTemplateExpression>node);
case SyntaxKind.TypeAssertionExpression:
return emit((<TypeAssertion>node).expression);
case SyntaxKind.AsExpression:
return emit((<AsExpression>node).expression);
case SyntaxKind.NonNullExpression:
return emit((<AssertionExpression | NonNullExpression>node).expression);
case SyntaxKind.ParenthesizedExpression:
return emitParenExpression(<ParenthesizedExpression>node);
case SyntaxKind.FunctionDeclaration:
@ -8177,6 +8251,16 @@ const _super = (function (geti, seti) {
if (declarationFilePath) {
emitSkipped = writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
}
}
}
}

View File

@ -177,6 +177,8 @@ namespace ts {
case SyntaxKind.AsExpression:
return visitNode(cbNode, (<AsExpression>node).expression) ||
visitNode(cbNode, (<AsExpression>node).type);
case SyntaxKind.NonNullExpression:
return visitNode(cbNode, (<NonNullExpression>node).expression);
case SyntaxKind.ConditionalExpression:
return visitNode(cbNode, (<ConditionalExpression>node).condition) ||
visitNode(cbNode, (<ConditionalExpression>node).questionToken) ||
@ -301,6 +303,9 @@ namespace ts {
case SyntaxKind.ImportClause:
return visitNode(cbNode, (<ImportClause>node).name) ||
visitNode(cbNode, (<ImportClause>node).namedBindings);
case SyntaxKind.GlobalModuleExportDeclaration:
return visitNode(cbNode, (<GlobalModuleExportDeclaration>node).name);
case SyntaxKind.NamespaceImport:
return visitNode(cbNode, (<NamespaceImport>node).name);
case SyntaxKind.NamedImports:
@ -407,21 +412,8 @@ namespace ts {
return result;
}
/* @internal */
export function getScriptKindFromFileName(fileName: string): ScriptKind {
const ext = fileName.substr(fileName.lastIndexOf("."));
switch (ext.toLowerCase()) {
case ".js":
return ScriptKind.JS;
case ".jsx":
return ScriptKind.JSX;
case ".ts":
return ScriptKind.TS;
case ".tsx":
return ScriptKind.TSX;
default:
return ScriptKind.TS;
}
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
// Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
@ -551,12 +543,7 @@ namespace ts {
let parseErrorBeforeNextFinishedNode = false;
export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile {
// Using scriptKind as a condition handles both:
// - 'scriptKind' is unspecified and thus it is `undefined`
// - 'scriptKind' is set and it is `Unknown` (0)
// If the 'scriptKind' is 'undefined' or 'Unknown' then attempt
// to get the ScriptKind from the file name.
scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName);
scriptKind = ensureScriptKind(fileName, scriptKind);
initializeState(fileName, _sourceText, languageVersion, _syntaxCursor, scriptKind);
@ -1143,7 +1130,7 @@ namespace ts {
if (token === SyntaxKind.DefaultKeyword) {
return lookAhead(nextTokenIsClassOrFunction);
}
return token !== SyntaxKind.AsteriskToken && token !== SyntaxKind.OpenBraceToken && canFollowModifier();
return token !== SyntaxKind.AsteriskToken && token !== SyntaxKind.AsKeyword && token !== SyntaxKind.OpenBraceToken && canFollowModifier();
}
if (token === SyntaxKind.DefaultKeyword) {
return nextTokenIsClassOrFunction();
@ -2023,7 +2010,7 @@ namespace ts {
}
function isStartOfParameter(): boolean {
return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken;
return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken || token === SyntaxKind.ThisKeyword;
}
function setModifiers(node: Node, modifiers: ModifiersArray) {
@ -2035,15 +2022,19 @@ namespace ts {
function parseParameter(): ParameterDeclaration {
const node = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
if (token === SyntaxKind.ThisKeyword) {
node.name = createIdentifier(/*isIdentifier*/true, undefined);
node.type = parseParameterType();
return finishNode(node);
}
node.decorators = parseDecorators();
setModifiers(node, parseModifiers());
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
node.name = parseIdentifierOrPattern();
if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifierKind(token)) {
// in cases like
// 'use strict'
@ -2081,11 +2072,11 @@ namespace ts {
}
function fillSignature(
returnToken: SyntaxKind,
yieldContext: boolean,
awaitContext: boolean,
requireCompleteParameterList: boolean,
signature: SignatureDeclaration): void {
returnToken: SyntaxKind,
yieldContext: boolean,
awaitContext: boolean,
requireCompleteParameterList: boolean,
signature: SignatureDeclaration): void {
const returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken;
signature.typeParameters = parseTypeParameters();
@ -2376,12 +2367,14 @@ namespace ts {
case SyntaxKind.NumberKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
// If these are followed by a dot, then parse these out as a dotted type reference instead.
const node = tryParse(parseKeywordAndNoDot);
return node || parseTypeReference();
case SyntaxKind.StringLiteral:
return parseStringLiteralTypeNode();
case SyntaxKind.VoidKeyword:
case SyntaxKind.NullKeyword:
return parseTokenNode<TypeNode>();
case SyntaxKind.ThisKeyword: {
const thisKeyword = parseThisTypeNode();
@ -2413,6 +2406,8 @@ namespace ts {
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.VoidKeyword:
case SyntaxKind.UndefinedKeyword:
case SyntaxKind.NullKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.TypeOfKeyword:
case SyntaxKind.OpenBraceToken:
@ -2482,7 +2477,7 @@ namespace ts {
// Skip modifiers
parseModifiers();
}
if (isIdentifier()) {
if (isIdentifier() || token === SyntaxKind.ThisKeyword) {
nextToken();
return true;
}
@ -3739,6 +3734,14 @@ namespace ts {
continue;
}
if (token === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
nextToken();
const nonNullExpression = <NonNullExpression>createNode(SyntaxKind.NonNullExpression, expression.pos);
nonNullExpression.expression = expression;
expression = finishNode(nonNullExpression);
continue;
}
// when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
if (!inDecoratorContext() && parseOptional(SyntaxKind.OpenBracketToken)) {
const indexedAccess = <ElementAccessExpression>createNode(SyntaxKind.ElementAccessExpression, expression.pos);
@ -3954,7 +3957,7 @@ namespace ts {
function tryParseAccessorDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): AccessorDeclaration {
if (parseContextualModifier(SyntaxKind.GetKeyword)) {
return parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, decorators, modifiers);
return addJSDocComment(parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, decorators, modifiers));
}
else if (parseContextualModifier(SyntaxKind.SetKeyword)) {
return parseAccessorDeclaration(SyntaxKind.SetAccessor, fullStart, decorators, modifiers);
@ -4418,7 +4421,8 @@ namespace ts {
continue;
case SyntaxKind.GlobalKeyword:
return nextToken() === SyntaxKind.OpenBraceToken;
nextToken();
return token === SyntaxKind.OpenBraceToken || token === SyntaxKind.Identifier || token === SyntaxKind.ExportKeyword;
case SyntaxKind.ImportKeyword:
nextToken();
@ -4427,7 +4431,8 @@ namespace ts {
case SyntaxKind.ExportKeyword:
nextToken();
if (token === SyntaxKind.EqualsToken || token === SyntaxKind.AsteriskToken ||
token === SyntaxKind.OpenBraceToken || token === SyntaxKind.DefaultKeyword) {
token === SyntaxKind.OpenBraceToken || token === SyntaxKind.DefaultKeyword ||
token === SyntaxKind.AsKeyword) {
return true;
}
continue;
@ -4611,9 +4616,15 @@ namespace ts {
return parseImportDeclarationOrImportEqualsDeclaration(fullStart, decorators, modifiers);
case SyntaxKind.ExportKeyword:
nextToken();
return token === SyntaxKind.DefaultKeyword || token === SyntaxKind.EqualsToken ?
parseExportAssignment(fullStart, decorators, modifiers) :
parseExportDeclaration(fullStart, decorators, modifiers);
switch (token) {
case SyntaxKind.DefaultKeyword:
case SyntaxKind.EqualsToken:
return parseExportAssignment(fullStart, decorators, modifiers);
case SyntaxKind.AsKeyword:
return parseGlobalModuleExportDeclaration(fullStart, decorators, modifiers);
default:
return parseExportDeclaration(fullStart, decorators, modifiers);
}
default:
if (decorators || modifiers) {
// We reached this point because we encountered decorators and/or modifiers and assumed a declaration
@ -5282,6 +5293,20 @@ namespace ts {
return nextToken() === SyntaxKind.SlashToken;
}
function parseGlobalModuleExportDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): GlobalModuleExportDeclaration {
const exportDeclaration = <GlobalModuleExportDeclaration>createNode(SyntaxKind.GlobalModuleExportDeclaration, fullStart);
exportDeclaration.decorators = decorators;
exportDeclaration.modifiers = modifiers;
parseExpected(SyntaxKind.AsKeyword);
parseExpected(SyntaxKind.NamespaceKeyword);
exportDeclaration.name = parseIdentifier();
parseExpected(SyntaxKind.SemicolonToken);
return finishNode(exportDeclaration);
}
function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray<Decorator>, modifiers: ModifiersArray): ImportEqualsDeclaration | ImportDeclaration {
parseExpected(SyntaxKind.ImportKeyword);
const afterImportPos = scanner.getStartPos();
@ -5484,6 +5509,7 @@ namespace ts {
function processReferenceComments(sourceFile: SourceFile): void {
const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText);
const referencedFiles: FileReference[] = [];
const typeReferenceDirectives: FileReference[] = [];
const amdDependencies: { path: string; name: string }[] = [];
let amdModuleName: string;
@ -5510,7 +5536,12 @@ namespace ts {
sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
const diagnosticMessage = referencePathMatchResult.diagnosticMessage;
if (fileReference) {
referencedFiles.push(fileReference);
if (referencePathMatchResult.isTypeReferenceDirective) {
typeReferenceDirectives.push(fileReference);
}
else {
referencedFiles.push(fileReference);
}
}
if (diagnosticMessage) {
parseDiagnostics.push(createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
@ -5542,6 +5573,7 @@ namespace ts {
}
sourceFile.referencedFiles = referencedFiles;
sourceFile.typeReferenceDirectives = typeReferenceDirectives;
sourceFile.amdDependencies = amdDependencies;
sourceFile.moduleName = amdModuleName;
}

File diff suppressed because it is too large Load Diff

View File

@ -114,6 +114,7 @@ namespace ts {
"try": SyntaxKind.TryKeyword,
"type": SyntaxKind.TypeKeyword,
"typeof": SyntaxKind.TypeOfKeyword,
"undefined": SyntaxKind.UndefinedKeyword,
"var": SyntaxKind.VarKeyword,
"void": SyntaxKind.VoidKeyword,
"while": SyntaxKind.WhileKeyword,

View File

@ -1,8 +1,8 @@
/// <reference path="core.ts"/>
namespace ts {
export type FileWatcherCallback = (path: string, removed?: boolean) => void;
export type DirectoryWatcherCallback = (path: string) => void;
export type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
export type DirectoryWatcherCallback = (directoryName: string) => void;
export interface System {
args: string[];
@ -11,7 +11,7 @@ namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@ -20,12 +20,14 @@ namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
interface WatchedFile {
filePath: Path;
fileName: string;
callback: FileWatcherCallback;
mtime?: Date;
}
@ -35,7 +37,7 @@ namespace ts {
}
export interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
@ -226,6 +228,7 @@ namespace ts {
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
const _crypto = require("crypto");
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
@ -244,13 +247,13 @@ namespace ts {
return;
}
_fs.stat(watchedFile.filePath, (err: any, stats: any) => {
_fs.stat(watchedFile.fileName, (err: any, stats: any) => {
if (err) {
watchedFile.callback(watchedFile.filePath);
watchedFile.callback(watchedFile.fileName);
}
else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
watchedFile.mtime = getModifiedTime(watchedFile.filePath);
watchedFile.callback(watchedFile.filePath, watchedFile.mtime.getTime() === 0);
watchedFile.mtime = getModifiedTime(watchedFile.fileName);
watchedFile.callback(watchedFile.fileName, watchedFile.mtime.getTime() === 0);
}
});
}
@ -278,11 +281,11 @@ namespace ts {
}, interval);
}
function addFile(filePath: Path, callback: FileWatcherCallback): WatchedFile {
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
const file: WatchedFile = {
filePath,
fileName,
callback,
mtime: getModifiedTime(filePath)
mtime: getModifiedTime(fileName)
};
watchedFiles.push(file);
@ -306,26 +309,26 @@ namespace ts {
}
function createWatchedFileSet() {
const dirWatchers = createFileMap<DirectoryWatcher>();
const dirWatchers: Map<DirectoryWatcher> = {};
// One file can have multiple watchers
const fileWatcherCallbacks = createFileMap<FileWatcherCallback[]>();
const fileWatcherCallbacks: Map<FileWatcherCallback[]> = {};
return { addFile, removeFile };
function reduceDirWatcherRefCountForFile(filePath: Path) {
const dirPath = getDirectoryPath(filePath);
if (dirWatchers.contains(dirPath)) {
const watcher = dirWatchers.get(dirPath);
function reduceDirWatcherRefCountForFile(fileName: string) {
const dirName = getDirectoryPath(fileName);
if (hasProperty(dirWatchers, dirName)) {
const watcher = dirWatchers[dirName];
watcher.referenceCount -= 1;
if (watcher.referenceCount <= 0) {
watcher.close();
dirWatchers.remove(dirPath);
delete dirWatchers[dirName];
}
}
}
function addDirWatcher(dirPath: Path): void {
if (dirWatchers.contains(dirPath)) {
const watcher = dirWatchers.get(dirPath);
function addDirWatcher(dirPath: string): void {
if (hasProperty(dirWatchers, dirPath)) {
const watcher = dirWatchers[dirPath];
watcher.referenceCount += 1;
return;
}
@ -336,52 +339,52 @@ namespace ts {
(eventName: string, relativeFileName: string) => fileEventHandler(eventName, relativeFileName, dirPath)
);
watcher.referenceCount = 1;
dirWatchers.set(dirPath, watcher);
dirWatchers[dirPath] = watcher;
return;
}
function addFileWatcherCallback(filePath: Path, callback: FileWatcherCallback): void {
if (fileWatcherCallbacks.contains(filePath)) {
fileWatcherCallbacks.get(filePath).push(callback);
function addFileWatcherCallback(filePath: string, callback: FileWatcherCallback): void {
if (hasProperty(fileWatcherCallbacks, filePath)) {
fileWatcherCallbacks[filePath].push(callback);
}
else {
fileWatcherCallbacks.set(filePath, [callback]);
fileWatcherCallbacks[filePath] = [callback];
}
}
function addFile(filePath: Path, callback: FileWatcherCallback): WatchedFile {
addFileWatcherCallback(filePath, callback);
addDirWatcher(getDirectoryPath(filePath));
function addFile(fileName: string, callback: FileWatcherCallback): WatchedFile {
addFileWatcherCallback(fileName, callback);
addDirWatcher(getDirectoryPath(fileName));
return { filePath, callback };
return { fileName, callback };
}
function removeFile(watchedFile: WatchedFile) {
removeFileWatcherCallback(watchedFile.filePath, watchedFile.callback);
reduceDirWatcherRefCountForFile(watchedFile.filePath);
removeFileWatcherCallback(watchedFile.fileName, watchedFile.callback);
reduceDirWatcherRefCountForFile(watchedFile.fileName);
}
function removeFileWatcherCallback(filePath: Path, callback: FileWatcherCallback) {
if (fileWatcherCallbacks.contains(filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks.get(filePath));
function removeFileWatcherCallback(filePath: string, callback: FileWatcherCallback) {
if (hasProperty(fileWatcherCallbacks, filePath)) {
const newCallbacks = copyListRemovingItem(callback, fileWatcherCallbacks[filePath]);
if (newCallbacks.length === 0) {
fileWatcherCallbacks.remove(filePath);
delete fileWatcherCallbacks[filePath];
}
else {
fileWatcherCallbacks.set(filePath, newCallbacks);
fileWatcherCallbacks[filePath] = newCallbacks;
}
}
}
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: Path) {
function fileEventHandler(eventName: string, relativeFileName: string, baseDirPath: string) {
// When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
const filePath = typeof relativeFileName !== "string"
const fileName = typeof relativeFileName !== "string"
? undefined
: toPath(relativeFileName, baseDirPath, createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
: ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath);
// Some applications save a working file via rename operations
if ((eventName === "change" || eventName === "rename") && fileWatcherCallbacks.contains(filePath)) {
for (const fileCallback of fileWatcherCallbacks.get(filePath)) {
fileCallback(filePath);
if ((eventName === "change" || eventName === "rename") && hasProperty(fileWatcherCallbacks, fileName)) {
for (const fileCallback of fileWatcherCallbacks[fileName]) {
fileCallback(fileName);
}
}
}
@ -498,6 +501,11 @@ namespace ts {
const files = _fs.readdirSync(path || ".").sort();
const directories: string[] = [];
for (const current of files) {
// This is necessary because on some file system node fails to exclude
// "." and "..". See https://github.com/nodejs/node/issues/4002
if (current === "." || current === "..") {
continue;
}
const name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
const stat = _fs.statSync(name);
@ -526,18 +534,18 @@ namespace ts {
},
readFile,
writeFile,
watchFile: (filePath, callback) => {
watchFile: (fileName, callback) => {
// Node 4.0 stabilized the `fs.watch` function on Windows which avoids polling
// and is more efficient than `fs.watchFile` (ref: https://github.com/nodejs/node/pull/2649
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
const watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet;
const watchedFile = watchSet.addFile(filePath, callback);
const watchedFile = watchSet.addFile(fileName, callback);
return {
close: () => watchSet.removeFile(watchedFile)
};
},
watchDirectory: (path, callback, recursive) => {
watchDirectory: (directoryName, callback, recursive) => {
// Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
// (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
let options: any;
@ -549,7 +557,7 @@ namespace ts {
}
return _fs.watch(
path,
directoryName,
options,
(eventName: string, relativeFileName: string) => {
// In watchDirectory we only care about adding and removing files (when event name is
@ -557,7 +565,7 @@ namespace ts {
// event name is "change")
if (eventName === "rename") {
// When deleting a file, the passed baseFileName is null
callback(!relativeFileName ? relativeFileName : normalizePath(combinePaths(path, relativeFileName)));
callback(!relativeFileName ? relativeFileName : normalizePath(combinePaths(directoryName, relativeFileName)));
};
}
);
@ -579,6 +587,19 @@ namespace ts {
return process.cwd();
},
readDirectory,
getModifiedTime(path) {
try {
return _fs.statSync(path).mtime;
}
catch (e) {
return undefined;
}
},
createHash(data) {
const hash = _crypto.createHash("md5");
hash.update(data);
return hash.digest("hex");
},
getMemoryUsage() {
if (global.gc) {
global.gc();
@ -621,7 +642,10 @@ namespace ts {
};
}
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
@ -629,9 +653,6 @@ namespace ts {
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
else if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else {
return undefined; // Unsupported host
}

View File

@ -14,6 +14,20 @@ namespace ts {
}
}
function reportEmittedFiles(files: string[], host: CompilerHost): void {
if (!files || files.length == 0) {
return;
}
const currentDir = sys.getCurrentDirectory();
for (const file of files) {
const filepath = getNormalizedAbsolutePath(file, currentDir);
sys.write(`TSFILE: ${filepath}${sys.newLine}`);
}
}
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
@ -30,11 +44,9 @@ namespace ts {
const territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
if (!trySetLanguageAndTerritory(language, territory, errors) &&
!trySetLanguageAndTerritory(language, undefined, errors)) {
errors.push(createCompilerDiagnostic(Diagnostics.Unsupported_locale_0, locale));
return false;
// Either ways do not fail, and fallback to the English diagnostic strings.
if (!trySetLanguageAndTerritory(language, territory, errors)) {
trySetLanguageAndTerritory(language, undefined, errors);
}
return true;
@ -108,7 +120,6 @@ namespace ts {
sys.write(output);
}
const redForegroundEscapeSequence = "\u001b[91m";
const yellowForegroundEscapeSequence = "\u001b[93m";
const blueForegroundEscapeSequence = "\u001b[93m";
@ -240,11 +251,6 @@ namespace ts {
return typeof JSON === "object" && typeof JSON.parse === "function";
}
function isWatchSet(options: CompilerOptions) {
// Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}
export function executeCommandLine(args: string[]): void {
const commandLine = parseCommandLine(args);
let configFileName: string; // Configuration file name (if any)
@ -338,8 +344,7 @@ namespace ts {
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (configFileName) {
const configFilePath = toPath(configFileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
configFileWatcher = sys.watchFile(configFilePath, configFileChanged);
configFileWatcher = sys.watchFile(configFileName, configFileChanged);
}
if (sys.watchDirectory && configFileName) {
const directory = ts.getDirectoryPath(configFileName);
@ -386,6 +391,10 @@ namespace ts {
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
return;
}
if (isWatchSet(configParseResult.options) && !sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), /* compilerHost */ undefined);
sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
return configParseResult;
}
@ -445,10 +454,9 @@ namespace ts {
}
// Use default host function
const sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
if (sourceFile && isWatchSet(compilerOptions)) {
if (sourceFile && isWatchSet(compilerOptions) && sys.watchFile) {
// Attach a file watcher
const filePath = toPath(sourceFile.fileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
sourceFile.fileWatcher = sys.watchFile(filePath, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
}
return sourceFile;
}
@ -600,6 +608,8 @@ namespace ts {
reportDiagnostics(sortAndDeduplicateDiagnostics(diagnostics), compilerHost);
reportEmittedFiles(emitOutput.emittedFiles, compilerHost);
if (emitOutput.emitSkipped && diagnostics.length > 0) {
// If the emitter didn't emit anything, then pass that value along.
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
@ -651,6 +661,8 @@ namespace ts {
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap: Map<string[]> = {}; // Map between option.description and list of option.type if it is a kind
for (let i = 0; i < optsList.length; i++) {
const option = optsList[i];
@ -671,7 +683,22 @@ namespace ts {
usageText += getParamType(option);
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(option.description));
let description: string;
if (option.name === "lib") {
description = getDiagnosticText(option.description);
const options: string[] = [];
const element = (<CommandLineOptionOfListType>option).element;
forEachKey(<Map<number | string>>element.type, key => {
options.push(`'${key}'`);
});
optionsDescriptionMap[description] = options;
}
else {
description = getDiagnosticText(option.description);
}
descriptionColumn.push(description);
// Set the new margin for the description column if necessary.
marginLength = Math.max(usageText.length, marginLength);
@ -687,7 +714,16 @@ namespace ts {
for (let i = 0; i < usageColumn.length; i++) {
const usage = usageColumn[i];
const description = descriptionColumn[i];
const kindsList = optionsDescriptionMap[description];
output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine;
if (kindsList) {
output += makePadding(marginLength + 4);
for (const kind of kindsList) {
output += kind + " ";
}
output += sys.newLine;
}
}
sys.write(output);

View File

@ -171,6 +171,7 @@ namespace ts {
StringKeyword,
SymbolKeyword,
TypeKeyword,
UndefinedKeyword,
FromKeyword,
GlobalKeyword,
OfKeyword, // LastKeyword and LastToken
@ -240,6 +241,7 @@ namespace ts {
OmittedExpression,
ExpressionWithTypeArguments,
AsExpression,
NonNullExpression,
// Misc
TemplateSpan,
@ -274,6 +276,7 @@ namespace ts {
ModuleDeclaration,
ModuleBlock,
CaseBlock,
GlobalModuleExportDeclaration,
ImportEqualsDeclaration,
ImportDeclaration,
ImportClause,
@ -402,6 +405,7 @@ namespace ts {
JavaScriptFile = 1 << 27, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 28, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 29, // If we've computed data from children and cached it in this node
HasJsxSpreadAttribute = 1 << 30,
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async,
AccessibilityModifier = Public | Private | Protected,
@ -474,6 +478,11 @@ namespace ts {
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
}
// Transient identifier node (marked by id === -1)
export interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
// @kind(SyntaxKind.QualifiedName)
export interface QualifiedName extends Node {
// Must have same layout as PropertyAccess
@ -967,6 +976,8 @@ namespace ts {
name: Identifier;
}
export type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
// @kind(SyntaxKind.ElementAccessExpression)
export interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
@ -1011,6 +1022,11 @@ namespace ts {
export type AssertionExpression = TypeAssertion | AsExpression;
// @kind(SyntaxKind.NonNullExpression)
export interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
/// A JSX expression of the form <TagName attrs>...</TagName>
// @kind(SyntaxKind.JsxElement)
export interface JsxElement extends PrimaryExpression {
@ -1208,6 +1224,8 @@ namespace ts {
block: Block;
}
export type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
export interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@ -1324,6 +1342,12 @@ namespace ts {
name: Identifier;
}
// @kind(SyntaxKind.GlobalModuleImport)
export interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
// @kind(SyntaxKind.ExportDeclaration)
export interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
@ -1513,6 +1537,7 @@ namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
@ -1537,6 +1562,8 @@ namespace ts {
/* @internal */ externalModuleIndicator: Node;
// The first node that causes this file to be a CommonJS module
/* @internal */ commonJsModuleIndicator: Node;
// True if the file was a root file in a compilation or a /// reference targets
/* @internal */ wasReferenced?: boolean;
/* @internal */ identifiers: Map<string>;
/* @internal */ nodeCount: number;
@ -1558,6 +1585,7 @@ namespace ts {
// It is used to resolve module names in the checker.
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<ResolvedModule>;
/* @internal */ resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
}
@ -1573,7 +1601,7 @@ namespace ts {
}
export interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
export class OperationCanceledException { }
@ -1634,6 +1662,7 @@ namespace ts {
/* @internal */ getTypeCount(): number;
/* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection;
/* @internal */ getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
// For testing purposes only.
/* @internal */ structureIsReused?: boolean;
}
@ -1684,6 +1713,7 @@ namespace ts {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[]; // Array of files the compiler wrote to disk
/* @internal */ sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
}
@ -1693,6 +1723,7 @@ namespace ts {
getSourceFiles(): SourceFile[];
getSourceFile(fileName: string): SourceFile;
getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
}
export interface TypeChecker {
@ -1710,6 +1741,7 @@ namespace ts {
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@ -1753,7 +1785,7 @@ namespace ts {
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@ -1788,6 +1820,7 @@ namespace ts {
WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature
InElementType = 0x00000040, // Writing an array or union element type
UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type)
InFirstTypeArgument = 0x00000100, // Writing first type argument of the instantiated type
}
export const enum SymbolFormatFlags {
@ -1889,6 +1922,7 @@ namespace ts {
writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult;
isEntityNameVisible(entityName: EntityName | Expression, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
@ -1899,6 +1933,8 @@ namespace ts {
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile;
getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[];
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
}
export const enum SymbolFlags {
@ -1994,6 +2030,7 @@ namespace ts {
members?: SymbolTable; // Class, interface or literal instance members
exports?: SymbolTable; // Module exports
globalExports?: SymbolTable; // Conditional global UMD exports
/* @internal */ id?: number; // Unique id (used to look up SymbolLinks)
/* @internal */ mergeId?: number; // Merge id (used to look up merged symbol)
/* @internal */ parent?: Symbol; // Parent symbol
@ -2016,7 +2053,9 @@ namespace ts {
exportsChecked?: boolean; // True if exports of external module have been checked
isDeclarationWithCollidingName?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
exportsSomeValue?: boolean; // true if module exports some value (not just types)
exportsSomeValue?: boolean; // True if module exports some value (not just types)
firstAssignmentChecked?: boolean; // True if first assignment node has been computed
firstAssignment?: Node; // First assignment node (undefined if no assignments)
}
/* @internal */
@ -2059,7 +2098,7 @@ namespace ts {
isVisible?: boolean; // Is this node visible
generatedName?: string; // Generated name for module, enum, or import declaration
generatedNames?: Map<string>; // Generated names table for source file
assignmentChecks?: Map<boolean>; // Cache of assignment checks
assignmentMap?: Map<boolean>; // Cached map of references assigned within this node
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
importOnRightSide?: Symbol; // for import declarations - import that appear on the right side
jsxFlags?: JsxFlags; // flags for knowing what kind of element/attributes we're dealing with
@ -2093,7 +2132,7 @@ namespace ts {
/* @internal */
FreshObjectLiteral = 0x00100000, // Fresh object literal type
/* @internal */
ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type
ContainsUndefinedOrNull = 0x00200000, // Type is or contains undefined or null type
/* @internal */
ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type
/* @internal */
@ -2102,6 +2141,8 @@ namespace ts {
ThisType = 0x02000000, // This type
ObjectLiteralPatternWithComputedProperties = 0x04000000, // Object literal type implied by binding pattern has computed properties
/* @internal */
Nullable = Undefined | Null,
/* @internal */
Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null,
/* @internal */
@ -2249,6 +2290,7 @@ namespace ts {
declaration: SignatureDeclaration; // Originating declaration
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: Symbol[]; // Parameters
thisType?: Type; // type of this-type
/* @internal */
resolvedReturnType: Type; // Resolved return type
/* @internal */
@ -2285,6 +2327,7 @@ namespace ts {
/* @internal */
export interface TypeMapper {
(t: TypeParameter): Type;
mappedTypes?: Type[]; // Types mapped by this mapper
instantiations?: Type[]; // Cache of instantiations created using this type mapper.
context?: InferenceContext; // The inference context this mapper was created from.
// Only inference mappers have this set (in createInferenceMapper).
@ -2367,6 +2410,8 @@ namespace ts {
export type PathSubstitutions = Map<string[]>;
export type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
export interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
@ -2381,6 +2426,7 @@ namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@ -2390,6 +2436,7 @@ namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@ -2419,10 +2466,13 @@ namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
/* @internal */ stripInternal?: boolean;
// Skip checking lib.d.ts to help speed up tests.
@ -2430,7 +2480,32 @@ namespace ts {
// Do not perform validation of output file name in transpile scenarios
/* @internal */ suppressOutputPathCheck?: boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
/* @internal */
// When options come from a config file, its path is recorded here
configFilePath?: string;
/* @internal */
// Path used to used to compute primary search locations
typesRoot?: string;
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
export interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
export interface DiscoverTypingsInfo {
fileNames: string[]; // The file names that belong to the same project.
projectRootPath: string; // The path to the project root directory
safeListPath: string; // The path used to retrieve the safe list
packageNameToTypingLocation: Map<string>; // The map of package names to their cached typing locations
typingOptions: TypingOptions; // Used to customize the typing inference process
compilerOptions: CompilerOptions; // Used as a source for typing inference
}
export enum ModuleKind {
@ -2491,6 +2566,7 @@ namespace ts {
export interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
@ -2498,7 +2574,7 @@ namespace ts {
/* @internal */
export interface CommandLineOptionBase {
name: string;
type: "string" | "number" | "boolean" | "object" | Map<number>; // a value of a primitive type, or an object literal mapping named values to actual values
type: "string" | "number" | "boolean" | "object" | "list" | Map<number | string>; // a value of a primitive type, or an object literal mapping named values to actual values
isFilePath?: boolean; // True if option value is a path or fileName
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
description?: DiagnosticMessage; // The message describing what the command line switch does
@ -2514,8 +2590,7 @@ namespace ts {
/* @internal */
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
type: Map<number>; // an object literal mapping named values to actual values
error: DiagnosticMessage; // The error given when the argument does not fit a customized 'type'
type: Map<number | string>; // an object literal mapping named values to actual values
}
/* @internal */
@ -2524,7 +2599,13 @@ namespace ts {
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption;
export interface CommandLineOptionOfListType extends CommandLineOptionBase {
type: "list";
element: CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType;
}
/* @internal */
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption | CommandLineOptionOfListType;
/* @internal */
export const enum CharacterCodes {
@ -2688,10 +2769,23 @@ namespace ts {
failedLookupLocations: string[];
}
export interface ResolvedTypeReferenceDirective {
// True if the type declaration file was found in a primary lookup location
primary: boolean;
// The location of the .d.ts file we located, or undefined if resolution failed
resolvedFileName?: string;
}
export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
@ -2706,6 +2800,10 @@ namespace ts {
* 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
*/
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
}
export interface TextSpan {

View File

@ -6,6 +6,7 @@ namespace ts {
fileReference?: FileReference;
diagnosticMessage?: DiagnosticMessage;
isNoDefaultLib?: boolean;
isTypeReferenceDirective?: boolean;
}
export interface SynthesizedNode extends Node {
@ -118,6 +119,43 @@ namespace ts {
sourceFile.resolvedModules[moduleNameText] = resolvedModule;
}
export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = {};
}
sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective;
}
/* @internal */
export function moduleResolutionIsEqualTo(oldResolution: ResolvedModule, newResolution: ResolvedModule): boolean {
return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport;
}
/* @internal */
export function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirective, newResolution: ResolvedTypeReferenceDirective): boolean {
return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
}
/* @internal */
export function hasChangesInResolutions<T>(names: string[], newResolutions: T[], oldResolutions: Map<T>, comparer: (oldResolution: T, newResolution: T) => boolean): boolean {
if (names.length !== newResolutions.length) {
return false;
}
for (let i = 0; i < names.length; i++) {
const newResolution = newResolutions[i];
const oldResolution = oldResolutions && hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined;
const changed =
oldResolution
? !newResolution || !comparer(oldResolution, newResolution)
: newResolution;
if (changed) {
return true;
}
}
return false;
}
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
@ -179,6 +217,33 @@ namespace ts {
return node.pos;
}
export function getEndLinePosition(line: number, sourceFile: SourceFile): number {
Debug.assert(line >= 0);
const lineStarts = getLineStarts(sourceFile);
const lineIndex = line;
const sourceText = sourceFile.text;
if (lineIndex + 1 === lineStarts.length) {
// last line - return EOF
return sourceText.length - 1;
}
else {
// current line start
const start = lineStarts[lineIndex];
// take the start position of the next line - 1 = it should be some line break
let pos = lineStarts[lineIndex + 1] - 1;
Debug.assert(isLineBreak(sourceText.charCodeAt(pos)));
// walk backwards skipping line breaks, stop the the beginning of current line.
// i.e:
// <some text>
// $ <- end of line for this position should match the start position
while (start <= pos && isLineBreak(sourceText.charCodeAt(pos))) {
pos--;
}
return pos;
}
}
// Returns true if this node is missing from the actual source code. A 'missing' node is different
// from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
// in the tree), it is definitely missing. However, a node may be defined, but still be
@ -364,6 +429,20 @@ namespace ts {
return createTextSpanFromBounds(start, scanner.getTextPos());
}
function getErrorSpanForArrowFunction(sourceFile: SourceFile, node: ArrowFunction): TextSpan {
const pos = skipTrivia(sourceFile.text, node.pos);
if (node.body && node.body.kind === SyntaxKind.Block) {
const { line: startLine } = getLineAndCharacterOfPosition(sourceFile, node.body.pos);
const { line: endLine } = getLineAndCharacterOfPosition(sourceFile, node.body.end);
if (startLine < endLine) {
// The arrow function spans multiple lines,
// make the error span be the first line, inclusive.
return createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
}
}
return createTextSpanFromBounds(pos, node.end);
}
export function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan {
let errorNode = node;
switch (node.kind) {
@ -392,6 +471,8 @@ namespace ts {
case SyntaxKind.TypeAliasDeclaration:
errorNode = (<Declaration>node).name;
break;
case SyntaxKind.ArrowFunction:
return getErrorSpanForArrowFunction(sourceFile, <ArrowFunction>node);
}
if (errorNode === undefined) {
@ -407,10 +488,6 @@ namespace ts {
return createTextSpanFromBounds(pos, errorNode.end);
}
export function isExternalModule(file: SourceFile): boolean {
return file.externalModuleIndicator !== undefined;
}
export function isExternalOrCommonJsModule(file: SourceFile): boolean {
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
}
@ -502,6 +579,7 @@ namespace ts {
}
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export let fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
export let fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export function isTypeNode(node: Node): boolean {
@ -515,6 +593,7 @@ namespace ts {
case SyntaxKind.StringKeyword:
case SyntaxKind.BooleanKeyword:
case SyntaxKind.SymbolKeyword:
case SyntaxKind.UndefinedKeyword:
return true;
case SyntaxKind.VoidKeyword:
return node.parent.kind !== SyntaxKind.VoidExpression;
@ -956,6 +1035,16 @@ namespace ts {
return node.kind === SyntaxKind.ElementAccessExpression;
}
export function isJSXTagName(node: Node) {
const parent = node.parent;
if (parent.kind === SyntaxKind.JsxOpeningElement ||
parent.kind === SyntaxKind.JsxSelfClosingElement ||
parent.kind === SyntaxKind.JsxClosingElement) {
return (<JsxOpeningLikeElement>parent).tagName === node;
}
return false;
}
export function isExpression(node: Node): boolean {
switch (node.kind) {
case SyntaxKind.SuperKeyword:
@ -972,6 +1061,7 @@ namespace ts {
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ClassExpression:
@ -996,9 +1086,9 @@ namespace ts {
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeQuery;
return node.parent.kind === SyntaxKind.TypeQuery || isJSXTagName(node);
case SyntaxKind.Identifier:
if (node.parent.kind === SyntaxKind.TypeQuery) {
if (node.parent.kind === SyntaxKind.TypeQuery || isJSXTagName(node)) {
return true;
}
// fall through
@ -1106,9 +1196,16 @@ namespace ts {
return isRequire && (!checkArgumentIsStringLiteral || (<CallExpression>expression).arguments[0].kind === SyntaxKind.StringLiteral);
}
export function isSingleOrDoubleQuote(charCode: number) {
return charCode === CharacterCodes.singleQuote || charCode === CharacterCodes.doubleQuote;
}
/// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
/// assignments we treat as special in the binder
export function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind {
if (!isInJavaScriptFile(expression)) {
return SpecialPropertyAssignmentKind.None;
}
if (expression.kind !== SyntaxKind.BinaryExpression) {
return SpecialPropertyAssignmentKind.None;
}
@ -1280,23 +1377,26 @@ namespace ts {
return isRestParameter(lastOrUndefined(s.parameters));
}
export function isRestParameter(node: ParameterDeclaration) {
if (node) {
if (node.flags & NodeFlags.JavaScriptFile) {
if (node.type && node.type.kind === SyntaxKind.JSDocVariadicType) {
return true;
}
export function hasDeclaredRestParameter(s: SignatureDeclaration): boolean {
return isDeclaredRestParam(lastOrUndefined(s.parameters));
}
const paramTag = getCorrespondingJSDocParameterTag(node);
if (paramTag && paramTag.typeExpression) {
return paramTag.typeExpression.type.kind === SyntaxKind.JSDocVariadicType;
}
export function isRestParameter(node: ParameterDeclaration) {
if (node && (node.flags & NodeFlags.JavaScriptFile)) {
if (node.type && node.type.kind === SyntaxKind.JSDocVariadicType) {
return true;
}
return node.dotDotDotToken !== undefined;
const paramTag = getCorrespondingJSDocParameterTag(node);
if (paramTag && paramTag.typeExpression) {
return paramTag.typeExpression.type.kind === SyntaxKind.JSDocVariadicType;
}
}
return isDeclaredRestParam(node);
}
return false;
export function isDeclaredRestParam(node: ParameterDeclaration) {
return node && node.dotDotDotToken !== undefined;
}
export function isLiteralKind(kind: SyntaxKind): boolean {
@ -1475,6 +1575,7 @@ namespace ts {
// export default ...
export function isAliasSymbolDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.ImportEqualsDeclaration ||
node.kind === SyntaxKind.GlobalModuleExportDeclaration ||
node.kind === SyntaxKind.ImportClause && !!(<ImportClause>node).name ||
node.kind === SyntaxKind.NamespaceImport ||
node.kind === SyntaxKind.ImportSpecifier ||
@ -1536,25 +1637,26 @@ namespace ts {
};
}
else {
const matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
if (matchResult) {
const refMatchResult = fullTripleSlashReferencePathRegEx.exec(comment);
const refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment);
if (refMatchResult || refLibResult) {
const start = commentRange.pos;
const end = commentRange.end;
return {
fileReference: {
pos: start,
end: end,
fileName: matchResult[3]
fileName: (refMatchResult || refLibResult)[3]
},
isNoDefaultLib: false
};
}
else {
return {
diagnosticMessage: Diagnostics.Invalid_reference_directive_syntax,
isNoDefaultLib: false
isNoDefaultLib: false,
isTypeReferenceDirective: !!refLibResult
};
}
return {
diagnosticMessage: Diagnostics.Invalid_reference_directive_syntax,
isNoDefaultLib: false
};
}
}
@ -2110,10 +2212,10 @@ namespace ts {
return combinePaths(newDirPath, sourceFilePath);
}
export function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean) {
export function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]) {
host.writeFile(fileName, data, writeByteOrderMark, hostErrorMessage => {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
});
}, sourceFiles);
}
export function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number) {
@ -2406,6 +2508,7 @@ namespace ts {
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.TaggedTemplateExpression:
@ -2629,6 +2732,11 @@ namespace ts {
}
return carriageReturnLineFeed;
}
export function isWatchSet(options: CompilerOptions) {
// Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}
}
namespace ts {
@ -2866,4 +2974,13 @@ namespace ts {
export function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean {
return node.flags & NodeFlags.AccessibilityModifier && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent);
}
export function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
}

View File

@ -1,7 +1,7 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/// <reference path="typeWriter.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
const enum CompilerTestType {
Conformance,
@ -88,7 +88,7 @@ class CompilerBaselineRunner extends RunnerBase {
toBeCompiled = [];
otherFiles = [];
if (/require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
if (testCaseContent.settings["noImplicitReferences"] || /require\(/.test(lastUnit.content) || /reference\spath/.test(lastUnit.content)) {
toBeCompiled.push({ unitName: this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content });
units.forEach(unit => {
if (unit.name !== lastUnit.name) {
@ -102,6 +102,10 @@ class CompilerBaselineRunner extends RunnerBase {
});
}
if (tsConfigOptions && tsConfigOptions.configFilePath !== undefined) {
tsConfigOptions.configFilePath = ts.combinePaths(rootDir, tsConfigOptions.configFilePath);
}
const output = Harness.Compiler.compileFiles(
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ undefined);
@ -140,7 +144,7 @@ class CompilerBaselineRunner extends RunnerBase {
});
it (`Correct module resolution tracing for ${fileName}`, () => {
if (options.traceModuleResolution) {
if (options.traceResolution) {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".trace.json"), () => {
return JSON.stringify(result.traceResults || [], undefined, 4);
});
@ -252,125 +256,128 @@ class CompilerBaselineRunner extends RunnerBase {
}
// NEWTODO: Type baselines
if (result.errors.length === 0) {
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type displayed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
}
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
}
if (e1 || e2) {
throw e1 || e2;
}
if (result.errors.length !== 0) {
return;
}
function checkBaseLines(isSymbolBaseLine: boolean) {
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type displayed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
}
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
}
if (e1 || e2) {
throw e1 || e2;
}
return;
function checkBaseLines(isSymbolBaseLine: boolean) {
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
const codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
let typeInfo = [formattedLine];
const existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
const currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
const typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push("\r\n");
}
}
}
else {
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join("");
else {
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
const codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
let typeInfo = [formattedLine];
const existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
const currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
const typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push("\r\n");
}
}
}
else {
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join("");
}
});
});
}

View File

@ -18,7 +18,7 @@
/// <reference path="harnessLanguageService.ts" />
/// <reference path="harness.ts" />
/// <reference path="fourslashRunner.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace FourSlash {
ts.disableIncrementalParsing = false;
@ -221,8 +221,8 @@ namespace FourSlash {
function tryAdd(path: string) {
const inputFile = inputFiles[path];
if (inputFile && !Harness.isLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile);
if (inputFile && !Harness.isDefaultLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile, /*isRootFile*/ true);
return true;
}
}
@ -247,6 +247,10 @@ namespace FourSlash {
// Create a new Services Adapter
this.cancellationToken = new TestCancellationToken();
const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
if (compilationOptions.typesRoot) {
compilationOptions.typesRoot = ts.getNormalizedAbsolutePath(compilationOptions.typesRoot, this.basePath);
}
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = languageServiceAdapter.getLanguageService();
@ -268,7 +272,7 @@ namespace FourSlash {
if (startResolveFileRef) {
// Add the entry-point file itself into the languageServiceShimHost
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content);
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content, /*isRootFile*/ true);
const resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content);
const referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles;
@ -291,17 +295,19 @@ namespace FourSlash {
// Check if no-default-lib flag is false and if so add default library
if (!resolvedResult.isLibFile) {
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
}
else {
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
ts.forEachKey(this.inputFiles, fileName => {
if (!Harness.isLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName]);
if (!Harness.isDefaultLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName], /*isRootFile*/ true);
}
});
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
this.formatCodeOptions = {
@ -356,14 +362,14 @@ namespace FourSlash {
}
// Opens a file given its 0-based index or fileName
public openFile(index: number, content?: string): void;
public openFile(name: string, content?: string): void;
public openFile(indexOrName: any, content?: string) {
public openFile(index: number, content?: string, scriptKindName?: string): void;
public openFile(name: string, content?: string, scriptKindName?: string): void;
public openFile(indexOrName: any, content?: string, scriptKindName?: string) {
const fileToOpen: FourSlashFile = this.findFile(indexOrName);
fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName);
this.activeFile = fileToOpen;
// Let the host know that this file is now open
this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content);
this.languageServiceAdapterHost.openFile(fileToOpen.fileName, content, scriptKindName);
}
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
@ -649,7 +655,7 @@ namespace FourSlash {
this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind);
}
else {
this.raiseError(`No completions at position '${ this.currentCaretPosition }' when looking for '${ symbol }'.`);
this.raiseError(`No completions at position '${this.currentCaretPosition}' when looking for '${symbol}'.`);
}
}
@ -1414,7 +1420,7 @@ namespace FourSlash {
return;
}
const incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName);
const incrementalSourceFile = this.languageService.getNonBoundSourceFile(this.activeFile.fileName);
Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined);
const incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics;
@ -1752,13 +1758,13 @@ namespace FourSlash {
const actual = (<ts.server.SessionClient>this.languageService).getProjectInfo(
this.activeFile.fileName,
/* needFileNameList */ true
);
);
assert.equal(
expected.join(","),
actual.fileNames.map( file => {
actual.fileNames.map(file => {
return file.replace(this.basePath + "/", "");
}).join(",")
);
}).join(",")
);
}
}
@ -1844,6 +1850,37 @@ namespace FourSlash {
});
}
public verifyBraceCompletionAtPostion(negative: boolean, openingBrace: string) {
const openBraceMap: ts.Map<ts.CharacterCodes> = {
"(": ts.CharacterCodes.openParen,
"{": ts.CharacterCodes.openBrace,
"[": ts.CharacterCodes.openBracket,
"'": ts.CharacterCodes.singleQuote,
'"': ts.CharacterCodes.doubleQuote,
"`": ts.CharacterCodes.backtick,
"<": ts.CharacterCodes.lessThan
};
const charCode = openBraceMap[openingBrace];
if (!charCode) {
this.raiseError(`Invalid openingBrace '${openingBrace}' specified.`);
}
const position = this.currentCaretPosition;
const validBraceCompletion = this.languageService.isValidBraceCompletionAtPostion(this.activeFile.fileName, position, charCode);
if (!negative && !validBraceCompletion) {
this.raiseError(`${position} is not a valid brace completion position for ${openingBrace}`);
}
if (negative && validBraceCompletion) {
this.raiseError(`${position} is a valid brace completion position for ${openingBrace}`);
}
}
public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) {
const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition);
@ -2233,7 +2270,7 @@ namespace FourSlash {
};
const host = Harness.Compiler.createCompilerHost(
[ fourslashFile, testFile ],
[fourslashFile, testFile],
(fn, contents) => result = contents,
ts.ScriptTarget.Latest,
Harness.IO.useCaseSensitiveFileNames(),
@ -2258,7 +2295,7 @@ namespace FourSlash {
function runCode(code: string, state: TestState): void {
// Compile and execute the test
const wrappedCode =
`(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) {
`(function(test, goTo, verify, edit, debug, format, cancellation, classification, verifyOperationIsCancelled) {
${code}
})`;
try {
@ -2372,7 +2409,7 @@ ${code}
}
}
}
// TODO: should be '==='?
// TODO: should be '==='?
}
else if (line == "" || lineLength === 0) {
// Previously blank lines between fourslash content caused it to be considered as 2 files,
@ -2753,10 +2790,10 @@ namespace FourSlashInterface {
// Opens a file, given either its index as it
// appears in the test source, or its filename
// as specified in the test metadata
public file(index: number, content?: string): void;
public file(name: string, content?: string): void;
public file(indexOrName: any, content?: string): void {
this.state.openFile(indexOrName, content);
public file(index: number, content?: string, scriptKindName?: string): void;
public file(name: string, content?: string, scriptKindName?: string): void;
public file(indexOrName: any, content?: string, scriptKindName?: string): void {
this.state.openFile(indexOrName, content, scriptKindName);
}
}
@ -2864,6 +2901,10 @@ namespace FourSlashInterface {
public verifyDefinitionsName(name: string, containerName: string) {
this.state.verifyDefinitionsName(this.negative, name, containerName);
}
public isValidBraceCompletionAtPostion(openingBrace: string) {
this.state.verifyBraceCompletionAtPostion(this.negative, openingBrace);
}
}
export class Verify extends VerifyNegatable {
@ -3082,7 +3123,7 @@ namespace FourSlashInterface {
this.state.getSemanticDiagnostics(expected);
}
public ProjectInfo(expected: string []) {
public ProjectInfo(expected: string[]) {
this.state.verifyProjectInfo(expected);
}
}

View File

@ -1,7 +1,7 @@
///<reference path="fourslash.ts" />
///<reference path="harness.ts"/>
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
const enum FourSlashTestType {
Native,

View File

@ -23,7 +23,7 @@
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
@ -65,6 +65,11 @@ namespace Utils {
return Buffer ? (new Buffer(s)).toString("utf8") : s;
}
export function byteLength(s: string, encoding?: string): number {
// stub implementation if Buffer is not available (in-browser case)
return Buffer ? Buffer.byteLength(s, encoding) : s.length;
}
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
const environment = getExecutionEnvironment();
switch (environment) {
@ -809,15 +814,33 @@ namespace Harness {
const lineFeed = "\n";
export const defaultLibFileName = "lib.d.ts";
export const defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
const libFileNameSourceFileMap: ts.Map<ts.SourceFile> = {
[defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest)
};
export function getDefaultLibrarySourceFile(fileName = defaultLibFileName): ts.SourceFile {
if (!isDefaultLibraryFile(fileName)) {
return undefined;
}
if (!libFileNameSourceFileMap[fileName]) {
libFileNameSourceFileMap[fileName] = createSourceFileAndAssertInvariants(fileName, IO.readFile(libFolder + fileName), ts.ScriptTarget.Latest);
}
return libFileNameSourceFileMap[fileName];
}
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName;
}
// Cache these between executions so we don't have to re-parse them for every test
export const fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return Harness.IO.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
return fileName;
}
export function createCompilerHost(
@ -842,23 +865,21 @@ namespace Harness {
}
}
function getSourceFile(fn: string, languageVersion: ts.ScriptTarget) {
fn = ts.normalizePath(fn);
const path = ts.toPath(fn, currentDirectory, getCanonicalFileName);
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget) {
fileName = ts.normalizePath(fileName);
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
return fileMap.get(path);
}
else if (fn === fourslashFileName) {
else if (fileName === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
return fourslashSourceFile;
}
else {
if (fn === defaultLibFileName) {
return languageVersion === ts.ScriptTarget.ES6 ? defaultES6LibSourceFile : defaultLibSourceFile;
}
// Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC
return undefined;
// Return if it is other library file, otherwise return undefined
return getDefaultLibrarySourceFile(fileName);
}
}
@ -867,16 +888,21 @@ namespace Harness {
newLineKind === ts.NewLineKind.LineFeed ? lineFeed :
Harness.IO.newLine();
return {
getCurrentDirectory: () => currentDirectory,
getSourceFile,
getDefaultLibFileName: options => defaultLibFileName,
getDefaultLibFileName,
writeFile,
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => newLine,
fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
readFile: (fileName: string): string => { throw new Error("NotYetImplemented"); }
fileExists: fileName => {
return fileMap.contains(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
},
readFile: (fileName: string): string => {
return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)).getText();
}
};
}
@ -896,7 +922,8 @@ namespace Harness {
{ name: "fileName", type: "string" },
{ name: "libFiles", type: "string" },
{ name: "noErrorTruncation", type: "boolean" },
{ name: "suppressOutputPathCheck", type: "boolean" }
{ name: "suppressOutputPathCheck", type: "boolean" },
{ name: "noImplicitReferences", type: "boolean" }
];
let optionsIndex: ts.Map<ts.CommandLineOption>;
@ -920,6 +947,7 @@ namespace Harness {
}
const option = getCommandLineOption(name);
if (option) {
const errors: ts.Diagnostic[] = [];
switch (option.type) {
case "boolean":
options[option.name] = value.toLowerCase() === "true";
@ -928,15 +956,16 @@ namespace Harness {
options[option.name] = value;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
case "list":
options[option.name] = ts.parseListTypeOption(<ts.CommandLineOptionOfListType>option, value, errors);
break;
default:
let map = <ts.Map<number>>option.type;
let key = value.toLowerCase();
if (ts.hasProperty(map, key)) {
options[option.name] = map[key];
}
else {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
options[option.name] = ts.parseCustomTypeOption(<ts.CommandLineOptionOfCustomType>option, value, errors);
break;
}
if (errors.length > 0) {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
}
else {
@ -963,7 +992,6 @@ namespace Harness {
compilerOptions: ts.CompilerOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory: string): CompilationOutput {
const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.clone(compilerOptions) : { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
@ -1015,7 +1043,7 @@ namespace Harness {
options.newLine);
let traceResults: string[];
if (options.traceModuleResolution) {
if (options.traceResolution) {
traceResults = [];
compilerHost.trace = text => traceResults.push(text);
}
@ -1138,7 +1166,7 @@ namespace Harness {
// then they will be added twice thus triggering 'total errors' assertion with condition
// 'totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length
if (!error.file || !isLibraryFile(error.file.fileName)) {
if (!error.file || !isDefaultLibraryFile(error.file.fileName)) {
totalErrorsReportedInNonLibraryFiles++;
}
}
@ -1217,7 +1245,7 @@ namespace Harness {
});
const numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
return diagnostic.file && (isLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
return diagnostic.file && (isDefaultLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
});
const numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
@ -1461,6 +1489,7 @@ namespace Harness {
baseDir = ts.getNormalizedAbsolutePath(baseDir, rootDir);
}
tsConfig = ts.parseJsonConfigFileContent(configJson.config, parseConfigHost, baseDir);
tsConfig.options.configFilePath = data.name;
// delete entry from the list
testUnitData.splice(i, 1);
@ -1604,8 +1633,10 @@ namespace Harness {
}
}
export function isLibraryFile(filePath: string): boolean {
return (Path.getFileName(filePath) === "lib.d.ts") || (Path.getFileName(filePath) === "lib.core.d.ts");
export function isDefaultLibraryFile(filePath: string): boolean {
// We need to make sure that the filePath is prefixed with "lib." not just containing "lib." and end with ".d.ts"
const fileName = Path.getFileName(filePath);
return ts.startsWith(fileName, "lib.") && ts.endsWith(fileName, ".d.ts");
}
export function isBuiltFile(filePath: string): boolean {
@ -1613,7 +1644,7 @@ namespace Harness {
}
export function getDefaultLibraryFile(io: Harness.IO): Harness.Compiler.TestFile {
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + "lib.d.ts";
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + Harness.Compiler.defaultLibFileName;
return { unitName: libFile, content: io.readFile(libFile) };
}

View File

@ -9,7 +9,7 @@ namespace Harness.LanguageService {
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
private lineMap: number[] = undefined;
constructor(public fileName: string, public content: string) {
constructor(public fileName: string, public content: string, public isRootFile: boolean) {
this.setContent(content);
}
@ -135,7 +135,13 @@ namespace Harness.LanguageService {
public getFilenames(): string[] {
const fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript, (fileName) => { fileNames.push(fileName); });
ts.forEachValue(this.fileNameToScript, (scriptInfo) => {
if (scriptInfo.isRootFile) {
// only include root files here
// usually it means that we won't include lib.d.ts in the list of root files so it won't mess the computation of compilation root dir.
fileNames.push(scriptInfo.fileName);
}
});
return fileNames;
}
@ -143,8 +149,8 @@ namespace Harness.LanguageService {
return ts.lookUp(this.fileNameToScript, fileName);
}
public addScript(fileName: string, content: string): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content);
public addScript(fileName: string, content: string, isRootFile: boolean): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content, isRootFile);
}
public editScript(fileName: string, start: number, end: number, newText: string) {
@ -157,7 +163,7 @@ namespace Harness.LanguageService {
throw new Error("No script with name '" + fileName + "'");
}
public openFile(fileName: string, content?: string): void {
public openFile(fileName: string, content?: string, scriptKindName?: string): void {
}
/**
@ -177,7 +183,7 @@ namespace Harness.LanguageService {
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getCurrentDirectory(): string { return ""; }
getDefaultLibFileName(): string { return ""; }
getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; }
getScriptFileNames(): string[] { return this.getFilenames(); }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
const script = this.getScriptInfo(fileName);
@ -210,6 +216,7 @@ namespace Harness.LanguageService {
private nativeHost: NativeLanguageServiceHost;
public getModuleResolutionsForFile: (fileName: string) => string;
public getTypeReferenceDirectiveResolutionsForFile: (fileName: string) => string;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
@ -236,12 +243,25 @@ namespace Harness.LanguageService {
}
return JSON.stringify(imports);
};
this.getTypeReferenceDirectiveResolutionsForFile = (fileName) => {
const scriptInfo = this.getScriptInfo(fileName);
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false);
const resolutions: ts.Map<ts.ResolvedTypeReferenceDirective> = {};
const settings = this.nativeHost.getCompilationSettings();
for (const typeReferenceDirective of preprocessInfo.typeReferenceDirectives) {
const resolutionInfo = ts.resolveTypeReferenceDirective(typeReferenceDirective.fileName, fileName, settings, moduleResolutionHost);
if (resolutionInfo.resolvedTypeReferenceDirective.resolvedFileName) {
resolutions[typeReferenceDirective.fileName] = resolutionInfo.resolvedTypeReferenceDirective;
}
}
return JSON.stringify(resolutions);
};
}
}
getFilenames(): string[] { return this.nativeHost.getFilenames(); }
getScriptInfo(fileName: string): ScriptInfo { return this.nativeHost.getScriptInfo(fileName); }
addScript(fileName: string, content: string): void { this.nativeHost.addScript(fileName, content); }
addScript(fileName: string, content: string, isRootFile: boolean): void { this.nativeHost.addScript(fileName, content, isRootFile); }
editScript(fileName: string, start: number, end: number, newText: string): void { this.nativeHost.editScript(fileName, start, end, newText); }
positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter { return this.nativeHost.positionToLineAndCharacter(fileName, position); }
@ -417,13 +437,16 @@ namespace Harness.LanguageService {
getDocCommentTemplateAtPosition(fileName: string, position: number): ts.TextInsertion {
return unwrapJSONCallResult(this.shim.getDocCommentTemplateAtPosition(fileName, position));
}
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPostion(fileName, position, openingBrace));
}
getEmitOutput(fileName: string): ts.EmitOutput {
return unwrapJSONCallResult(this.shim.getEmitOutput(fileName));
}
getProgram(): ts.Program {
throw new Error("Program can not be marshaled across the shim layer.");
}
getSourceFile(fileName: string): ts.SourceFile {
getNonBoundSourceFile(fileName: string): ts.SourceFile {
throw new Error("SourceFile can not be marshaled across the shim layer.");
}
dispose(): void { this.shim.dispose({}); }
@ -442,6 +465,7 @@ namespace Harness.LanguageService {
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo {
let shimResult: {
referencedFiles: ts.IFileReference[];
typeReferenceDirectives: ts.IFileReference[];
importedFiles: ts.IFileReference[];
isLibFile: boolean;
};
@ -453,7 +477,8 @@ namespace Harness.LanguageService {
referencedFiles: [],
importedFiles: [],
ambientExternalModules: [],
isLibFile: shimResult.isLibFile
isLibFile: shimResult.isLibFile,
typeReferenceDirectives: []
};
ts.forEach(shimResult.referencedFiles, refFile => {
@ -472,6 +497,13 @@ namespace Harness.LanguageService {
});
});
ts.forEach(shimResult.typeReferenceDirectives, typeRefDirective => {
convertResult.importedFiles.push({
fileName: typeRefDirective.path,
pos: typeRefDirective.position,
end: typeRefDirective.position + typeRefDirective.length
});
});
return convertResult;
}
}
@ -496,9 +528,9 @@ namespace Harness.LanguageService {
this.client = client;
}
openFile(fileName: string, content?: string): void {
super.openFile(fileName, content);
this.client.openFile(fileName, content);
openFile(fileName: string, content?: string, scriptKindName?: "TS" | "JS" | "TSX" | "JSX"): void {
super.openFile(fileName, content, scriptKindName);
this.client.openFile(fileName, content, scriptKindName);
}
editScript(fileName: string, start: number, end: number, newText: string) {

View File

@ -1,7 +1,7 @@
/// <reference path="..\..\src\compiler\sys.ts" />
/// <reference path="..\..\src\harness\harness.ts" />
/// <reference path="..\..\src\harness\runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
interface FileInformation {
contents: string;
@ -237,8 +237,8 @@ namespace Playback {
), path));
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path, contents) => noOpReplay("writeFile"));
(path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path: string, contents: string) => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {

View File

@ -1,6 +1,6 @@
///<reference path="harness.ts" />
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
// Test case is json of below type in tests/cases/project/
interface ProjectRunnerTestCase {
@ -156,7 +156,7 @@ class ProjectRunner extends RunnerBase {
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile {
let sourceFile: ts.SourceFile = undefined;
if (fileName === Harness.Compiler.defaultLibFileName) {
sourceFile = languageVersion === ts.ScriptTarget.ES6 ? Harness.Compiler.defaultES6LibSourceFile : Harness.Compiler.defaultLibSourceFile;
sourceFile = Harness.Compiler.getDefaultLibrarySourceFile(Harness.Compiler.getDefaultLibFileName(compilerOptions));
}
else {
const text = getSourceFileText(fileName);
@ -412,7 +412,7 @@ class ProjectRunner extends RunnerBase {
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
const inputFiles = compilerResult.program ? ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => !Harness.isDefaultLibraryFile(sourceFile.fileName)),
sourceFile => {
return {
unitName: ts.isRootedDiskPath(sourceFile.fileName) ?

View File

@ -20,7 +20,7 @@
/// <reference path="rwcRunner.ts" />
/// <reference path="harness.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
let runners: RunnerBase[] = [];
let iterations = 1;

View File

@ -2,7 +2,7 @@
/// <reference path="runnerbase.ts" />
/// <reference path="loggedIO.ts" />
/// <reference path="..\compiler\commandLineParser.ts"/>
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace RWC {
function runWithIOLog(ioLog: IOLog, fn: (oldIO: Harness.IO) => void) {
@ -31,22 +31,20 @@ namespace RWC {
let otherFiles: Harness.Compiler.TestFile[] = [];
let compilerResult: Harness.Compiler.CompilerResult;
let compilerOptions: ts.CompilerOptions;
let baselineOpts: Harness.Baseline.BaselineOptions = {
const baselineOpts: Harness.Baseline.BaselineOptions = {
Subfolder: "rwc",
Baselinefolder: "internal/baselines"
};
let baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
const baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
let currentDirectory: string;
let useCustomLibraryFile: boolean;
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
// Therefore we have to clean out large objects after the test is done.
inputFiles = undefined;
otherFiles = undefined;
inputFiles = [];
otherFiles = [];
compilerResult = undefined;
compilerOptions = undefined;
baselineOpts = undefined;
baseName = undefined;
currentDirectory = undefined;
// useCustomLibraryFile is a flag specified in the json object to indicate whether to use built/local/lib.d.ts
// or to use lib.d.ts inside the json object. If the flag is true, use the lib.d.ts inside json file
@ -97,13 +95,13 @@ namespace RWC {
continue;
}
if (!Harness.isLibraryFile(fileRead.path)) {
if (!Harness.isDefaultLibraryFile(fileRead.path)) {
if (inInputList) {
continue;
}
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
}
else if (!opts.options.noLib && Harness.isLibraryFile(fileRead.path)) {
else if (!opts.options.noLib && Harness.isDefaultLibraryFile(fileRead.path)) {
if (!inInputList) {
// If useCustomLibraryFile is true, we will use lib.d.ts from json object
// otherwise use the lib.d.ts from built/local
@ -192,8 +190,9 @@ namespace RWC {
if (compilerResult.errors.length === 0) {
return null;
}
return Harness.Compiler.getErrorBaseline(inputFiles.concat(otherFiles), compilerResult.errors);
// Do not include the library in the baselines to avoid noise
const baselineFiles = inputFiles.concat(otherFiles).filter(f => !Harness.isDefaultLibraryFile(f.unitName));
return Harness.Compiler.getErrorBaseline(baselineFiles, compilerResult.errors);
}, false, baselineOpts);
});

View File

@ -1,6 +1,6 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
class Test262BaselineRunner extends RunnerBase {
private static basePath = "internal/cases/test262";

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,5 @@
/// <reference path="lib.dom.generated.d.ts" />
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}

70
src/lib/es2015.collection.d.ts vendored Normal file
View File

@ -0,0 +1,70 @@
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;

483
src/lib/es2015.core.d.ts vendored Normal file
View File

@ -0,0 +1,483 @@
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
big(): string;
/** Returns a <blink> HTML element */
blink(): string;
/** Returns a <b> HTML element */
bold(): string;
/** Returns a <tt> HTML element */
fixed(): string
/** Returns a <font> HTML element and sets the color attribute value */
fontcolor(color: string): string
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an <i> HTML element */
italics(): string;
/** Returns an <a> HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a <small> HTML element */
small(): string;
/** Returns a <strike> HTML element */
strike(): string;
/** Returns a <sub> HTML element */
sub(): string;
/** Returns a <sup> HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}

10
src/lib/es2015.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />

12
src/lib/es2015.generator.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;

373
src/lib/es2015.iterable.d.ts vendored Normal file
View File

@ -0,0 +1,373 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface IteratorResult<T> {
done: boolean;
value?: T;
}
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface IterableIterator<T> extends Iterator<T> { }
interface Array<T> {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
interface Map<K, V> {
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
}
interface MapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
}
interface WeakMap<K, V> { }
interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Promise<T> { }
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}

81
src/lib/es2015.promise.d.ts vendored Normal file
View File

@ -0,0 +1,81 @@
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject(reason: any): Promise<void>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;

22
src/lib/es2015.proxy.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
deleteProperty? (target: T, p: PropertyKey): boolean;
defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;

16
src/lib/es2015.reflect.d.ts vendored Normal file
View File

@ -0,0 +1,16 @@
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}

36
src/lib/es2015.symbol.d.ts vendored Normal file
View File

@ -0,0 +1,36 @@
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string|number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;

356
src/lib/es2015.symbol.wellknown.d.ts vendored Normal file
View File

@ -0,0 +1,356 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
interface Symbol {
readonly [Symbol.toStringTag]: "Symbol";
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
[Symbol.unscopables](): {
copyWithin: boolean;
entries: boolean;
fill: boolean;
find: boolean;
findIndex: boolean;
keys: boolean;
values: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
interface Promise<T> {
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
readonly [Symbol.species]: Function;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
[Symbol.species](): RegExpConstructor;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
readonly [Symbol.toStringTag]: "DataView";
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}

2
src/lib/es2016.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />

View File

@ -215,14 +215,16 @@ interface Function {
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(thisArg: any, argArray?: any): any;
apply<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U;
apply(this: Function, thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(thisArg: any, ...argArray: any[]): any;
call<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): U;
call(this: Function, thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body as the original function.
@ -230,7 +232,8 @@ interface Function {
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;
bind<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): (this: void, ...argArray: any[]) => U;
bind(this: Function, thisArg: any, ...argArray: any[]): any;
prototype: any;
readonly length: number;
@ -304,13 +307,13 @@ interface String {
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
match(regexp: string): RegExpMatchArray;
match(regexp: string): RegExpMatchArray | null;
/**
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
*/
match(regexp: RegExp): RegExpMatchArray;
match(regexp: RegExp): RegExpMatchArray | null;
/**
* Replaces text in a string, using a regular expression or search string.
@ -813,7 +816,7 @@ interface RegExp {
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/
exec(string: string): RegExpExecArray;
exec(string: string): RegExpExecArray | null;
/**
* Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
@ -836,7 +839,7 @@ interface RegExp {
lastIndex: number;
// Non-standard extensions
compile(): RegExp;
compile(): this;
}
interface RegExpConstructor {
@ -1061,7 +1064,7 @@ interface ReadonlyArray<T> {
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): T[];
filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => any, thisArg?: any): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@ -1108,7 +1111,7 @@ interface Array<T> {
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
pop(): T | undefined;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
@ -1126,7 +1129,7 @@ interface Array<T> {
/**
* Removes the first element from an array and returns it.
*/
shift(): T;
shift(): T | undefined;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
@ -1196,7 +1199,7 @@ interface Array<T> {
* @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[];
filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[];
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@ -1508,7 +1511,7 @@ interface Int8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): Int8Array;
filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -1519,7 +1522,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -1530,7 +1533,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -1781,7 +1784,7 @@ interface Uint8Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): Uint8Array;
filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -1792,7 +1795,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -1803,7 +1806,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2055,7 +2058,7 @@ interface Uint8ClampedArray {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): Uint8ClampedArray;
filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -2066,7 +2069,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2077,7 +2080,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2328,7 +2331,7 @@ interface Int16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): Int16Array;
filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -2339,7 +2342,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2350,7 +2353,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2602,7 +2605,7 @@ interface Uint16Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): Uint16Array;
filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -2613,7 +2616,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2624,7 +2627,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2875,7 +2878,7 @@ interface Int32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): Int32Array;
filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -2886,7 +2889,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2897,7 +2900,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3148,7 +3151,7 @@ interface Uint32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): Uint32Array;
filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -3159,7 +3162,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3170,7 +3173,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3421,7 +3424,7 @@ interface Float32Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): Float32Array;
filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -3432,7 +3435,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3443,7 +3446,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3695,7 +3698,7 @@ interface Float64Array {
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): Float64Array;
filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
@ -3706,7 +3709,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3717,7 +3720,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3904,3 +3907,204 @@ interface Float64ArrayConstructor {
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
declare const Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}

1333
src/lib/es6.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
/// <reference path="lib.core.d.ts" />

1
src/lib/importes5.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference path="lib.es5.d.ts" />

201
src/lib/intl.d.ts vendored
View File

@ -1,201 +0,0 @@
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}

View File

@ -13,10 +13,12 @@ interface EventListener {
}
interface AudioBuffer {
duration: number;
length: number;
numberOfChannels: number;
sampleRate: number;
readonly duration: number;
readonly length: number;
readonly numberOfChannels: number;
readonly sampleRate: number;
copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;
copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;
getChannelData(channel: number): Float32Array;
}
@ -26,8 +28,8 @@ declare var AudioBuffer: {
}
interface Blob {
size: number;
type: string;
readonly size: number;
readonly type: string;
msClose(): void;
msDetachStream(): any;
slice(start?: number, end?: number, contentType?: string): Blob;
@ -39,9 +41,9 @@ declare var Blob: {
}
interface CloseEvent extends Event {
code: number;
reason: string;
wasClean: boolean;
readonly code: number;
readonly reason: string;
readonly wasClean: boolean;
initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;
}
@ -58,6 +60,7 @@ interface Console {
dir(value?: any, ...optionalParams: any[]): void;
dirxml(value: any): void;
error(message?: any, ...optionalParams: any[]): void;
exception(message?: string, ...optionalParams: any[]): void;
group(groupTitle?: string): void;
groupCollapsed(groupTitle?: string): void;
groupEnd(): void;
@ -67,6 +70,7 @@ interface Console {
profile(reportName?: string): void;
profileEnd(): void;
select(element: any): void;
table(...data: any[]): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(message?: any, ...optionalParams: any[]): void;
@ -79,13 +83,13 @@ declare var Console: {
}
interface Coordinates {
accuracy: number;
altitude: number;
altitudeAccuracy: number;
heading: number;
latitude: number;
longitude: number;
speed: number;
readonly accuracy: number;
readonly altitude: number;
readonly altitudeAccuracy: number;
readonly heading: number;
readonly latitude: number;
readonly longitude: number;
readonly speed: number;
}
declare var Coordinates: {
@ -94,7 +98,7 @@ declare var Coordinates: {
}
interface DOMError {
name: string;
readonly name: string;
toString(): string;
}
@ -104,73 +108,73 @@ declare var DOMError: {
}
interface DOMException {
code: number;
message: string;
name: string;
readonly code: number;
readonly message: string;
readonly name: string;
toString(): string;
ABORT_ERR: number;
DATA_CLONE_ERR: number;
DOMSTRING_SIZE_ERR: number;
HIERARCHY_REQUEST_ERR: number;
INDEX_SIZE_ERR: number;
INUSE_ATTRIBUTE_ERR: number;
INVALID_ACCESS_ERR: number;
INVALID_CHARACTER_ERR: number;
INVALID_MODIFICATION_ERR: number;
INVALID_NODE_TYPE_ERR: number;
INVALID_STATE_ERR: number;
NAMESPACE_ERR: number;
NETWORK_ERR: number;
NOT_FOUND_ERR: number;
NOT_SUPPORTED_ERR: number;
NO_DATA_ALLOWED_ERR: number;
NO_MODIFICATION_ALLOWED_ERR: number;
PARSE_ERR: number;
QUOTA_EXCEEDED_ERR: number;
SECURITY_ERR: number;
SERIALIZE_ERR: number;
SYNTAX_ERR: number;
TIMEOUT_ERR: number;
TYPE_MISMATCH_ERR: number;
URL_MISMATCH_ERR: number;
VALIDATION_ERR: number;
WRONG_DOCUMENT_ERR: number;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
declare var DOMException: {
prototype: DOMException;
new(): DOMException;
ABORT_ERR: number;
DATA_CLONE_ERR: number;
DOMSTRING_SIZE_ERR: number;
HIERARCHY_REQUEST_ERR: number;
INDEX_SIZE_ERR: number;
INUSE_ATTRIBUTE_ERR: number;
INVALID_ACCESS_ERR: number;
INVALID_CHARACTER_ERR: number;
INVALID_MODIFICATION_ERR: number;
INVALID_NODE_TYPE_ERR: number;
INVALID_STATE_ERR: number;
NAMESPACE_ERR: number;
NETWORK_ERR: number;
NOT_FOUND_ERR: number;
NOT_SUPPORTED_ERR: number;
NO_DATA_ALLOWED_ERR: number;
NO_MODIFICATION_ALLOWED_ERR: number;
PARSE_ERR: number;
QUOTA_EXCEEDED_ERR: number;
SECURITY_ERR: number;
SERIALIZE_ERR: number;
SYNTAX_ERR: number;
TIMEOUT_ERR: number;
TYPE_MISMATCH_ERR: number;
URL_MISMATCH_ERR: number;
VALIDATION_ERR: number;
WRONG_DOCUMENT_ERR: number;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
interface DOMStringList {
length: number;
readonly length: number;
contains(str: string): boolean;
item(index: number): string;
[index: number]: string;
@ -182,11 +186,11 @@ declare var DOMStringList: {
}
interface ErrorEvent extends Event {
colno: number;
error: any;
filename: string;
lineno: number;
message: string;
readonly colno: number;
readonly error: any;
readonly filename: string;
readonly lineno: number;
readonly message: string;
initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;
}
@ -196,39 +200,39 @@ declare var ErrorEvent: {
}
interface Event {
bubbles: boolean;
readonly bubbles: boolean;
cancelBubble: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
readonly cancelable: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
readonly isTrusted: boolean;
returnValue: boolean;
srcElement: any;
target: EventTarget;
timeStamp: number;
type: string;
readonly srcElement: any;
readonly target: EventTarget;
readonly timeStamp: number;
readonly type: string;
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
declare var Event: {
prototype: Event;
new(type: string, eventInitDict?: EventInit): Event;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
interface EventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var EventTarget: {
@ -237,8 +241,9 @@ declare var EventTarget: {
}
interface File extends Blob {
lastModifiedDate: any;
name: string;
readonly lastModifiedDate: any;
readonly name: string;
readonly webkitRelativePath: string;
}
declare var File: {
@ -247,7 +252,7 @@ declare var File: {
}
interface FileList {
length: number;
readonly length: number;
item(index: number): File;
[index: number]: File;
}
@ -258,7 +263,7 @@ declare var FileList: {
}
interface FileReader extends EventTarget, MSBaseReader {
error: DOMError;
readonly error: DOMError;
readAsArrayBuffer(blob: Blob): void;
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): void;
@ -272,31 +277,31 @@ declare var FileReader: {
}
interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
readonly direction: string;
key: IDBKeyRange | IDBValidKey;
readonly primaryKey: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
continue(key?: IDBKeyRange | IDBValidKey): void;
delete(): IDBRequest;
update(value: any): IDBRequest;
NEXT: string;
NEXT_NO_DUPLICATE: string;
PREV: string;
PREV_NO_DUPLICATE: string;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
declare var IDBCursor: {
prototype: IDBCursor;
new(): IDBCursor;
NEXT: string;
NEXT_NO_DUPLICATE: string;
PREV: string;
PREV_NO_DUPLICATE: string;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
interface IDBCursorWithValue extends IDBCursor {
value: any;
readonly value: any;
}
declare var IDBCursorWithValue: {
@ -305,15 +310,17 @@ declare var IDBCursorWithValue: {
}
interface IDBDatabase extends EventTarget {
name: string;
objectStoreNames: DOMStringList;
readonly name: string;
readonly objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: number;
onversionchange: (ev: IDBVersionChangeEvent) => any;
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -337,15 +344,15 @@ declare var IDBFactory: {
interface IDBIndex {
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
readonly name: string;
readonly objectStore: IDBObjectStore;
readonly unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
openCursor(range?: IDBKeyRange, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
get(key: IDBKeyRange | IDBValidKey): IDBRequest;
getKey(key: IDBKeyRange | IDBValidKey): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
}
declare var IDBIndex: {
@ -354,37 +361,37 @@ declare var IDBIndex: {
}
interface IDBKeyRange {
lower: any;
lowerOpen: boolean;
upper: any;
upperOpen: boolean;
readonly lower: any;
readonly lowerOpen: boolean;
readonly upper: any;
readonly upperOpen: boolean;
}
declare var IDBKeyRange: {
prototype: IDBKeyRange;
new(): IDBKeyRange;
bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;
lowerBound(bound: any, open?: boolean): IDBKeyRange;
lowerBound(lower: any, open?: boolean): IDBKeyRange;
only(value: any): IDBKeyRange;
upperBound(bound: any, open?: boolean): IDBKeyRange;
upperBound(upper: any, open?: boolean): IDBKeyRange;
}
interface IDBObjectStore {
indexNames: DOMStringList;
readonly indexNames: DOMStringList;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
readonly name: string;
readonly transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
delete(key: IDBKeyRange | IDBValidKey): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
index(name: string): IDBIndex;
openCursor(range?: any, direction?: string): IDBRequest;
put(value: any, key?: any): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
}
declare var IDBObjectStore: {
@ -408,13 +415,13 @@ declare var IDBOpenDBRequest: {
}
interface IDBRequest extends EventTarget {
error: DOMError;
readonly error: DOMError;
onerror: (ev: Event) => any;
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
readonly readyState: string;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
readonly transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -426,17 +433,17 @@ declare var IDBRequest: {
}
interface IDBTransaction extends EventTarget {
db: IDBDatabase;
error: DOMError;
mode: string;
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
onabort: (ev: Event) => any;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
abort(): void;
objectStore(name: string): IDBObjectStore;
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
@ -446,14 +453,14 @@ interface IDBTransaction extends EventTarget {
declare var IDBTransaction: {
prototype: IDBTransaction;
new(): IDBTransaction;
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
}
interface IDBVersionChangeEvent extends Event {
newVersion: number;
oldVersion: number;
readonly newVersion: number;
readonly oldVersion: number;
}
declare var IDBVersionChangeEvent: {
@ -463,8 +470,8 @@ declare var IDBVersionChangeEvent: {
interface ImageData {
data: Uint8ClampedArray;
height: number;
width: number;
readonly height: number;
readonly width: number;
}
declare var ImageData: {
@ -483,29 +490,29 @@ interface MSApp {
execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void;
execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any;
getCurrentPriority(): string;
getHtmlPrintDocumentSourceAsync(htmlDoc: any): any;
getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike<any>;
getViewId(view: any): any;
isTaskScheduledAtPriorityOrHigher(priority: string): boolean;
pageHandlesAllApplicationActivations(enabled: boolean): void;
suppressSubdownloadCredentialPrompts(suppress: boolean): void;
terminateApp(exceptionObject: any): void;
CURRENT: string;
HIGH: string;
IDLE: string;
NORMAL: string;
readonly CURRENT: string;
readonly HIGH: string;
readonly IDLE: string;
readonly NORMAL: string;
}
declare var MSApp: MSApp;
interface MSAppAsyncOperation extends EventTarget {
error: DOMError;
readonly error: DOMError;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
readyState: number;
result: any;
readonly readyState: number;
readonly result: any;
start(): void;
COMPLETED: number;
ERROR: number;
STARTED: number;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -514,9 +521,9 @@ interface MSAppAsyncOperation extends EventTarget {
declare var MSAppAsyncOperation: {
prototype: MSAppAsyncOperation;
new(): MSAppAsyncOperation;
COMPLETED: number;
ERROR: number;
STARTED: number;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
}
interface MSBlobBuilder {
@ -530,7 +537,7 @@ declare var MSBlobBuilder: {
}
interface MSStream {
type: string;
readonly type: string;
msClose(): void;
msDetachStream(): any;
}
@ -541,7 +548,7 @@ declare var MSStream: {
}
interface MSStreamReader extends EventTarget, MSBaseReader {
error: DOMError;
readonly error: DOMError;
readAsArrayBuffer(stream: MSStream, size?: number): void;
readAsBinaryString(stream: MSStream, size?: number): void;
readAsBlob(stream: MSStream, size?: number): void;
@ -556,8 +563,8 @@ declare var MSStreamReader: {
}
interface MediaQueryList {
matches: boolean;
media: string;
readonly matches: boolean;
readonly media: string;
addListener(listener: MediaQueryListListener): void;
removeListener(listener: MediaQueryListListener): void;
}
@ -568,8 +575,8 @@ declare var MediaQueryList: {
}
interface MessageChannel {
port1: MessagePort;
port2: MessagePort;
readonly port1: MessagePort;
readonly port2: MessagePort;
}
declare var MessageChannel: {
@ -578,10 +585,10 @@ declare var MessageChannel: {
}
interface MessageEvent extends Event {
data: any;
origin: string;
ports: any;
source: any;
readonly data: any;
readonly origin: string;
readonly ports: any;
readonly source: any;
initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void;
}
@ -605,8 +612,8 @@ declare var MessagePort: {
}
interface Position {
coords: Coordinates;
timestamp: number;
readonly coords: Coordinates;
readonly timestamp: number;
}
declare var Position: {
@ -615,26 +622,26 @@ declare var Position: {
}
interface PositionError {
code: number;
message: string;
readonly code: number;
readonly message: string;
toString(): string;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
declare var PositionError: {
prototype: PositionError;
new(): PositionError;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
interface ProgressEvent extends Event {
lengthComputable: boolean;
loaded: number;
total: number;
readonly lengthComputable: boolean;
readonly loaded: number;
readonly total: number;
initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void;
}
@ -645,21 +652,21 @@ declare var ProgressEvent: {
interface WebSocket extends EventTarget {
binaryType: string;
bufferedAmount: number;
extensions: string;
readonly bufferedAmount: number;
readonly extensions: string;
onclose: (ev: CloseEvent) => any;
onerror: (ev: Event) => any;
onmessage: (ev: MessageEvent) => any;
onopen: (ev: Event) => any;
protocol: string;
readyState: number;
url: string;
readonly protocol: string;
readonly readyState: number;
readonly url: string;
close(code?: number, reason?: string): void;
send(data: any): void;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
OPEN: number;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
@ -670,10 +677,10 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
OPEN: number;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
}
interface Worker extends EventTarget, AbstractWorker {
@ -693,16 +700,15 @@ declare var Worker: {
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
msCaching: string;
onreadystatechange: (ev: ProgressEvent) => any;
readyState: number;
response: any;
responseBody: any;
responseText: string;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
responseType: string;
responseXML: any;
status: number;
statusText: string;
readonly responseXML: any;
readonly status: number;
readonly statusText: string;
timeout: number;
upload: XMLHttpRequestUpload;
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
abort(): void;
getAllResponseHeaders(): string;
@ -713,11 +719,11 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
send(data?: string): void;
send(data?: any): void;
setRequestHeader(header: string, value: string): void;
DONE: number;
HEADERS_RECEIVED: number;
LOADING: number;
OPENED: number;
UNSENT: number;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
@ -732,11 +738,11 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
declare var XMLHttpRequest: {
prototype: XMLHttpRequest;
new(): XMLHttpRequest;
DONE: number;
HEADERS_RECEIVED: number;
LOADING: number;
OPENED: number;
UNSENT: number;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
create(): XMLHttpRequest;
}
@ -762,12 +768,12 @@ interface MSBaseReader {
onloadend: (ev: ProgressEvent) => any;
onloadstart: (ev: Event) => any;
onprogress: (ev: ProgressEvent) => any;
readyState: number;
result: any;
readonly readyState: number;
readonly result: any;
abort(): void;
DONE: number;
EMPTY: number;
LOADING: number;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: number;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
@ -778,18 +784,18 @@ interface MSBaseReader {
}
interface NavigatorID {
appName: string;
appVersion: string;
platform: string;
product: string;
productSub: string;
userAgent: string;
vendor: string;
vendorSub: string;
readonly appName: string;
readonly appVersion: string;
readonly platform: string;
readonly product: string;
readonly productSub: string;
readonly userAgent: string;
readonly vendor: string;
readonly vendorSub: string;
}
interface NavigatorOnLine {
onLine: boolean;
readonly onLine: boolean;
}
interface WindowBase64 {
@ -798,7 +804,7 @@ interface WindowBase64 {
}
interface WindowConsole {
console: Console;
readonly console: Console;
}
interface XMLHttpRequestEventTarget {
@ -832,9 +838,9 @@ declare var FileReaderSync: {
}
interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole {
location: WorkerLocation;
readonly location: WorkerLocation;
onerror: (ev: Event) => any;
self: WorkerGlobalScope;
readonly self: WorkerGlobalScope;
close(): void;
msWriteProfilerMark(profilerMarkName: string): void;
toString(): string;
@ -849,14 +855,14 @@ declare var WorkerGlobalScope: {
}
interface WorkerLocation {
hash: string;
host: string;
hostname: string;
href: string;
pathname: string;
port: string;
protocol: string;
search: string;
readonly hash: string;
readonly host: string;
readonly hostname: string;
readonly href: string;
readonly pathname: string;
readonly port: string;
readonly protocol: string;
readonly search: string;
toString(): string;
}
@ -882,9 +888,9 @@ interface DedicatedWorkerGlobalScope {
}
interface WorkerUtils extends Object, WindowBase64 {
indexedDB: IDBFactory;
msIndexedDB: IDBFactory;
navigator: WorkerNavigator;
readonly indexedDB: IDBFactory;
readonly msIndexedDB: IDBFactory;
readonly navigator: WorkerNavigator;
clearImmediate(handle: number): void;
clearInterval(handle: number): void;
clearTimeout(handle: number): void;
@ -894,16 +900,6 @@ interface WorkerUtils extends Object, WindowBase64 {
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
@ -933,6 +929,9 @@ interface ProgressEventInit extends EventInit {
total?: number;
}
interface IDBArrayKey extends Array<IDBValidKey> {
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@ -971,9 +970,9 @@ declare var self: WorkerGlobalScope;
declare function close(): void;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function toString(): string;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare var indexedDB: IDBFactory;
declare var msIndexedDB: IDBFactory;
declare var navigator: WorkerNavigator;
@ -991,4 +990,5 @@ declare function postMessage(data: any): void;
declare var console: Console;
declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type IDBValidKey = number | string | Date | IDBArrayKey;

View File

@ -120,8 +120,8 @@ namespace ts.server {
return response;
}
openFile(fileName: string, content?: string): void {
var args: protocol.OpenRequestArgs = { file: fileName, fileContent: content };
openFile(fileName: string, content?: string, scriptKindName?: "TS" | "JS" | "TSX" | "JSX"): void {
var args: protocol.OpenRequestArgs = { file: fileName, fileContent: content, scriptKindName };
this.processRequest(CommandNames.Open, args);
}
@ -568,6 +568,10 @@ namespace ts.server {
throw new Error("Not Implemented Yet.");
}
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
throw new Error("Not Implemented Yet.");
}
getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[] {
var lineOffset = this.positionToOneBasedLineOffset(fileName, position);
var args: protocol.FileLocationRequestArgs = {
@ -613,7 +617,7 @@ namespace ts.server {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
getSourceFile(fileName: string): SourceFile {
getNonBoundSourceFile(fileName: string): SourceFile {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}

View File

@ -34,6 +34,7 @@ namespace ts.server {
fileWatcher: FileWatcher;
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
path: Path;
scriptKind: ScriptKind;
constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) {
this.path = toPath(fileName, host.getCurrentDirectory(), createGetCanonicalFileName(host.useCaseSensitiveFileNames));
@ -81,8 +82,14 @@ namespace ts.server {
}
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations {
lastCheckTime: number;
interface Timestamped {
lastCheckTime?: number;
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations, Timestamped {
}
interface TimestampedResolvedTypeReferenceDirective extends ResolvedTypeReferenceDirectiveWithFailedLookupLocations, Timestamped {
}
export class LSHost implements ts.LanguageServiceHost {
@ -90,13 +97,16 @@ namespace ts.server {
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.FileMap<ScriptInfo>;
roots: ScriptInfo[] = [];
private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>;
private resolvedTypeReferenceDirectives: ts.FileMap<Map<TimestampedResolvedTypeReferenceDirective>>;
private moduleResolutionHost: ts.ModuleResolutionHost;
private getCanonicalFileName: (fileName: string) => string;
constructor(public host: ServerHost, public project: Project) {
this.getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
this.resolvedModuleNames = createFileMap<Map<TimestampedResolvedModule>>();
this.resolvedTypeReferenceDirectives = createFileMap<Map<TimestampedResolvedTypeReferenceDirective>>();
this.filenameToScript = createFileMap<ScriptInfo>();
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
@ -105,46 +115,51 @@ namespace ts.server {
};
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
private resolveNamesWithLocalCache<T extends Timestamped & { failedLookupLocations: string[] }, R>(
names: string[],
containingFile: string,
cache: ts.FileMap<Map<T>>,
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T,
getResult: (s: T) => R): R[] {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = this.resolvedModuleNames.get(path);
const newResolutions: Map<TimestampedResolvedModule> = {};
const resolvedModules: ResolvedModule[] = [];
const currentResolutionsInFile = cache.get(path);
const newResolutions: Map<T> = {};
const resolvedModules: R[] = [];
const compilerOptions = this.getCompilationSettings();
for (const moduleName of moduleNames) {
for (const name of names) {
// check if this is a duplicate entry in the list
let resolution = lookUp(newResolutions, moduleName);
let resolution = lookUp(newResolutions, name);
if (!resolution) {
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
// ok, it is safe to use existing name resolution results
resolution = existingResolution;
}
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution = loader(name, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
newResolutions[name] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedModules.push(resolution.resolvedModule);
resolvedModules.push(getResult(resolution));
}
// replace old results with a new one
this.resolvedModuleNames.set(path, newResolutions);
cache.set(path, newResolutions);
return resolvedModules;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
function moduleResolutionIsValid(resolution: T): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedModule) {
if (getResult(resolution)) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
@ -156,6 +171,14 @@ namespace ts.server {
}
}
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective, m => m.resolvedTypeReferenceDirective);
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, resolveModuleName, m => m.resolvedModule);
}
getDefaultLibFileName() {
const nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
@ -172,6 +195,7 @@ namespace ts.server {
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
this.resolvedTypeReferenceDirectives.clear();
}
lineAffectsRefs(filename: string, line: number) {
@ -192,8 +216,16 @@ namespace ts.server {
return this.roots.map(root => root.fileName);
}
getScriptKind() {
return ScriptKind.Unknown;
getScriptKind(fileName: string) {
const info = this.getScriptInfo(fileName);
if (!info) {
return undefined;
}
if (!info.scriptKind) {
info.scriptKind = getScriptKindFromFileName(fileName);
}
return info.scriptKind;
}
getScriptVersion(filename: string) {
@ -212,6 +244,7 @@ namespace ts.server {
if (!info.isOpen) {
this.filenameToScript.remove(info.path);
this.resolvedModuleNames.remove(info.path);
this.resolvedTypeReferenceDirectives.remove(info.path);
}
}
@ -239,6 +272,7 @@ namespace ts.server {
this.filenameToScript.remove(info.path);
this.roots = copyListRemovingItem(info, this.roots);
this.resolvedModuleNames.remove(info.path);
this.resolvedTypeReferenceDirectives.remove(info.path);
}
}
@ -996,7 +1030,7 @@ namespace ts.server {
* @param filename is absolute pathname
* @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
openFile(fileName: string, openedByClient: boolean, fileContent?: string) {
openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind) {
fileName = ts.normalizePath(fileName);
let info = ts.lookUp(this.filenameToScriptInfo, fileName);
if (!info) {
@ -1011,12 +1045,11 @@ namespace ts.server {
}
if (content !== undefined) {
info = new ScriptInfo(this.host, fileName, content, openedByClient);
info.scriptKind = scriptKind;
info.setFormatOptions(this.getFormatCodeOptions());
this.filenameToScriptInfo[fileName] = info;
if (!info.isOpen) {
info.fileWatcher = this.host.watchFile(
toPath(fileName, fileName, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
_ => { this.watchedFileChanged(fileName); });
info.fileWatcher = this.host.watchFile(fileName, _ => { this.watchedFileChanged(fileName); });
}
}
}
@ -1062,9 +1095,9 @@ namespace ts.server {
* @param filename is absolute pathname
* @param fileContent is a known version of the file content that is more up to date than the one on disk
*/
openClientFile(fileName: string, fileContent?: string) {
openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind) {
this.openOrUpdateConfiguredProjectForFile(fileName);
const info = this.openFile(fileName, /*openedByClient*/ true, fileContent);
const info = this.openFile(fileName, /*openedByClient*/ true, fileContent, scriptKind);
this.addOpenFile(info);
this.printProjects();
return info;
@ -1235,9 +1268,7 @@ namespace ts.server {
}
}
project.finishGraph();
project.projectFileWatcher = this.host.watchFile(
toPath(configFilename, configFilename, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)),
_ => this.watchedProjectConfigFileChanged(project));
project.projectFileWatcher = this.host.watchFile(configFilename, _ => this.watchedProjectConfigFileChanged(project));
this.log("Add recursive watcher for: " + ts.getDirectoryPath(configFilename));
project.directoryWatcher = this.host.watchDirectory(
ts.getDirectoryPath(configFilename),
@ -1325,6 +1356,7 @@ namespace ts.server {
else {
const defaultOpts = ts.getDefaultCompilerOptions();
defaultOpts.allowNonTsExtensions = true;
defaultOpts.allowJs = true;
this.setCompilerOptions(defaultOpts);
}
this.languageService = ts.createLanguageService(this.host, this.documentRegistry);
@ -1337,7 +1369,7 @@ namespace ts.server {
}
isExternalModule(filename: string): boolean {
const sourceFile = this.languageService.getSourceFile(filename);
const sourceFile = this.languageService.getNonBoundSourceFile(filename);
return ts.isExternalModule(sourceFile);
}

View File

@ -518,6 +518,11 @@ declare namespace ts.server.protocol {
* Then the known content will be used upon opening instead of the disk copy
*/
fileContent?: string;
/**
* Used to specify the script kind of the file explicitly. It could be one of the following:
* "TS", "JS", "TSX", "JSX"
*/
scriptKindName?: "TS" | "JS" | "TSX" | "JSX";
}
/**

View File

@ -1,7 +1,7 @@
/// <reference path="node.d.ts" />
/// <reference path="session.ts" />
// used in fs.writeSync
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace ts.server {
const readline: NodeJS.ReadLine = require("readline");

View File

@ -559,9 +559,9 @@ namespace ts.server {
* @param fileName is the name of the file to be opened
* @param fileContent is a version of the file content that is known to be more up to date than the one on disk
*/
private openClientFile(fileName: string, fileContent?: string) {
private openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind) {
const file = ts.normalizePath(fileName);
this.projectService.openClientFile(file, fileContent);
this.projectService.openClientFile(file, fileContent, scriptKind);
}
private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody {
@ -1016,7 +1016,22 @@ namespace ts.server {
},
[CommandNames.Open]: (request: protocol.Request) => {
const openArgs = <protocol.OpenRequestArgs>request.arguments;
this.openClientFile(openArgs.file, openArgs.fileContent);
let scriptKind: ScriptKind;
switch (openArgs.scriptKindName) {
case "TS":
scriptKind = ScriptKind.TS;
break;
case "JS":
scriptKind = ScriptKind.JS;
break;
case "TSX":
scriptKind = ScriptKind.TSX;
break;
case "JSX":
scriptKind = ScriptKind.JSX;
break;
}
this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind);
return { responseRequired: false };
},
[CommandNames.Quickinfo]: (request: protocol.Request) => {

View File

@ -72,12 +72,20 @@ namespace ts.formatting {
if (line === 0) {
return [];
}
// get the span for the previous\current line
// After the enter key, the cursor is now at a new line. The new line may or may not contain non-whitespace characters.
// If the new line has only whitespaces, we won't want to format this line, because that would remove the indentation as
// trailing whitespaces. So the end of the formatting span should be the later one between:
// 1. the end of the previous line
// 2. the last non-whitespace character in the current line
let endOfFormatSpan = getEndLinePosition(line, sourceFile);
while (isWhiteSpace(sourceFile.text.charCodeAt(endOfFormatSpan)) && !isLineBreak(sourceFile.text.charCodeAt(endOfFormatSpan))) {
endOfFormatSpan--;
}
let span = {
// get start position for the previous line
pos: getStartPositionOfLine(line - 1, sourceFile),
// get end position for the current line (end value is exclusive so add 1 to the result)
end: getEndLinePosition(line, sourceFile) + 1
// end value is exclusive so add 1 to the result
end: endOfFormatSpan + 1
}
return formatSpan(span, sourceFile, options, rulesProvider, FormattingRequestKind.FormatOnEnter);
}
@ -720,25 +728,24 @@ namespace ts.formatting {
dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind, container) :
Constants.Unknown;
let indentNextTokenOrTrivia = true;
if (currentTokenInfo.leadingTrivia) {
let commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind, tokenIndentation, container);
let indentNextTokenOrTrivia = true;
for (let triviaItem of currentTokenInfo.leadingTrivia) {
if (!rangeContainsRange(originalRange, triviaItem)) {
continue;
}
const triviaInRange = rangeContainsRange(originalRange, triviaItem);
switch (triviaItem.kind) {
case SyntaxKind.MultiLineCommentTrivia:
indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
if (triviaInRange) {
indentMultilineComment(triviaItem, commentIndentation, /*firstLineIsIndented*/ !indentNextTokenOrTrivia);
}
indentNextTokenOrTrivia = false;
break;
case SyntaxKind.SingleLineCommentTrivia:
if (indentNextTokenOrTrivia) {
if (indentNextTokenOrTrivia && triviaInRange) {
insertIndentation(triviaItem.pos, commentIndentation, /*lineAdded*/ false);
indentNextTokenOrTrivia = false;
}
indentNextTokenOrTrivia = false;
break;
case SyntaxKind.NewLineTrivia:
indentNextTokenOrTrivia = true;
@ -748,7 +755,7 @@ namespace ts.formatting {
}
// indent token only if is it is in target range and does not overlap with any error ranges
if (tokenIndentation !== Constants.Unknown) {
if (tokenIndentation !== Constants.Unknown && indentNextTokenOrTrivia) {
insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded);
lastIndentedLine = tokenStart.line;

227
src/services/jsTyping.ts Normal file
View File

@ -0,0 +1,227 @@
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
/// <reference path='services.ts' />
/* @internal */
namespace ts.JsTyping {
export interface TypingResolutionHost {
directoryExists: (path: string) => boolean;
fileExists: (fileName: string) => boolean;
readFile: (path: string, encoding?: string) => string;
readDirectory: (path: string, extension?: string, exclude?: string[], depth?: number) => string[];
};
interface PackageJson {
_requiredBy?: string[];
dependencies?: Map<string>;
devDependencies?: Map<string>;
name?: string;
optionalDependencies?: Map<string>;
peerDependencies?: Map<string>;
typings?: string;
};
// A map of loose file names to library names
// that we are confident require typings
let safeList: Map<string>;
/**
* @param host is the object providing I/O related operations.
* @param fileNames are the file names that belong to the same project
* @param projectRootPath is the path to the project root directory
* @param safeListPath is the path used to retrieve the safe list
* @param packageNameToTypingLocation is the map of package names to their cached typing locations
* @param typingOptions are used to customize the typing inference process
* @param compilerOptions are used as a source for typing inference
*/
export function discoverTypings(
host: TypingResolutionHost,
fileNames: string[],
projectRootPath: Path,
safeListPath: Path,
packageNameToTypingLocation: Map<string>,
typingOptions: TypingOptions,
compilerOptions: CompilerOptions):
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
// A typing name to typing file path mapping
const inferredTypings: Map<string> = {};
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
}
// Only infer typings for .js and .jsx files
fileNames = filter(map(fileNames, normalizePath), f => scriptKindIs(f, /*LanguageServiceHost*/ undefined, ScriptKind.JS, ScriptKind.JSX));
if (!safeList) {
const result = readConfigFile(safeListPath, (path: string) => host.readFile(path));
if (result.config) {
safeList = result.config;
}
else {
safeList = {};
};
}
const filesToWatch: string[] = [];
// Directories to search for package.json, bower.json and other typing information
let searchDirs: string[] = [];
let exclude: string[] = [];
mergeTypings(typingOptions.include);
exclude = typingOptions.exclude || [];
const possibleSearchDirs = map(fileNames, getDirectoryPath);
if (projectRootPath !== undefined) {
possibleSearchDirs.push(projectRootPath);
}
searchDirs = deduplicate(possibleSearchDirs);
for (const searchDir of searchDirs) {
const packageJsonPath = combinePaths(searchDir, "package.json");
getTypingNamesFromJson(packageJsonPath, filesToWatch);
const bowerJsonPath = combinePaths(searchDir, "bower.json");
getTypingNamesFromJson(bowerJsonPath, filesToWatch);
const nodeModulesPath = combinePaths(searchDir, "node_modules");
getTypingNamesFromNodeModuleFolder(nodeModulesPath);
}
getTypingNamesFromSourceFileNames(fileNames);
// Add the cached typing locations for inferred typings that are already installed
for (const name in packageNameToTypingLocation) {
if (hasProperty(inferredTypings, name) && !inferredTypings[name]) {
inferredTypings[name] = packageNameToTypingLocation[name];
}
}
// Remove typings that the user has added to the exclude list
for (const excludeTypingName of exclude) {
delete inferredTypings[excludeTypingName];
}
const newTypingNames: string[] = [];
const cachedTypingPaths: string[] = [];
for (const typing in inferredTypings) {
if (inferredTypings[typing] !== undefined) {
cachedTypingPaths.push(inferredTypings[typing]);
}
else {
newTypingNames.push(typing);
}
}
return { cachedTypingPaths, newTypingNames, filesToWatch };
/**
* Merge a given list of typingNames to the inferredTypings map
*/
function mergeTypings(typingNames: string[]) {
if (!typingNames) {
return;
}
for (const typing of typingNames) {
if (!hasProperty(inferredTypings, typing)) {
inferredTypings[typing] = undefined;
}
}
}
/**
* Get the typing info from common package manager json files like package.json or bower.json
*/
function getTypingNamesFromJson(jsonPath: string, filesToWatch: string[]) {
const result = readConfigFile(jsonPath, (path: string) => host.readFile(path));
if (result.config) {
const jsonConfig: PackageJson = result.config;
filesToWatch.push(jsonPath);
if (jsonConfig.dependencies) {
mergeTypings(getKeys(jsonConfig.dependencies));
}
if (jsonConfig.devDependencies) {
mergeTypings(getKeys(jsonConfig.devDependencies));
}
if (jsonConfig.optionalDependencies) {
mergeTypings(getKeys(jsonConfig.optionalDependencies));
}
if (jsonConfig.peerDependencies) {
mergeTypings(getKeys(jsonConfig.peerDependencies));
}
}
}
/**
* Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
* should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
* to the 'angular-route' typing name.
* @param fileNames are the names for source files in the project
*/
function getTypingNamesFromSourceFileNames(fileNames: string[]) {
const jsFileNames = filter(fileNames, hasJavaScriptFileExtension);
const inferredTypingNames = map(jsFileNames, f => removeFileExtension(getBaseFileName(f.toLowerCase())));
const cleanedTypingNames = map(inferredTypingNames, f => f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""));
if (safeList === undefined) {
mergeTypings(cleanedTypingNames);
}
else {
mergeTypings(filter(cleanedTypingNames, f => hasProperty(safeList, f)));
}
const hasJsxFile = forEach(fileNames, f => scriptKindIs(f, /*LanguageServiceHost*/ undefined, ScriptKind.JSX));
if (hasJsxFile) {
mergeTypings(["react"]);
}
}
/**
* Infer typing names from node_module folder
* @param nodeModulesPath is the path to the "node_modules" folder
*/
function getTypingNamesFromNodeModuleFolder(nodeModulesPath: string) {
// Todo: add support for ModuleResolutionHost too
if (!host.directoryExists(nodeModulesPath)) {
return;
}
const typingNames: string[] = [];
const fileNames = host.readDirectory(nodeModulesPath, "*.json", /*exclude*/ undefined, /*depth*/ 2);
for (const fileName of fileNames) {
const normalizedFileName = normalizePath(fileName);
if (getBaseFileName(normalizedFileName) !== "package.json") {
continue;
}
const result = readConfigFile(normalizedFileName, (path: string) => host.readFile(path));
if (!result.config) {
continue;
}
const packageJson: PackageJson = result.config;
// npm 3's package.json contains a "_requiredBy" field
// we should include all the top level module names for npm 2, and only module names whose
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
if (packageJson._requiredBy &&
filter(packageJson._requiredBy, (r: string) => r[0] === "#" || r === "/").length === 0) {
continue;
}
// If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
// to download d.ts files from DefinitelyTyped
if (!packageJson.name) {
continue;
}
if (packageJson.typings) {
const absolutePath = getNormalizedAbsolutePath(packageJson.typings, getDirectoryPath(normalizedFileName));
inferredTypings[packageJson.name] = absolutePath;
}
else {
typingNames.push(packageJson.name);
}
}
mergeTypings(typingNames);
}
}
}

View File

@ -3,6 +3,12 @@
/* @internal */
namespace ts.NavigationBar {
export function getNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): ts.NavigationBarItem[] {
// TODO: Handle JS files differently in 'navbar' calls for now, but ideally we should unify
// the 'navbar' and 'navto' logic for TypeScript and JavaScript.
if (isSourceFileJavaScript(sourceFile)) {
return getJsNavigationBarItems(sourceFile, compilerOptions);
}
// If the source file has any child items, then it included in the tree
// and takes lexical ownership of all other top-level items.
let hasGlobalNode = false;
@ -130,7 +136,7 @@ namespace ts.NavigationBar {
return topLevelNodes;
}
function sortNodes(nodes: Node[]): Node[] {
return nodes.slice(0).sort((n1: Declaration, n2: Declaration) => {
if (n1.name && n2.name) {
@ -147,13 +153,27 @@ namespace ts.NavigationBar {
}
});
}
function addTopLevelNodes(nodes: Node[], topLevelNodes: Node[]): void {
nodes = sortNodes(nodes);
for (let node of nodes) {
switch (node.kind) {
case SyntaxKind.ClassDeclaration:
topLevelNodes.push(node);
for (const member of (<ClassDeclaration>node).members) {
if (member.kind === SyntaxKind.MethodDeclaration || member.kind === SyntaxKind.Constructor) {
type FunctionLikeMember = MethodDeclaration | ConstructorDeclaration;
if ((<FunctionLikeMember>member).body) {
// We do not include methods that does not have child functions in it, because of duplications.
if (hasNamedFunctionDeclarations((<Block>(<FunctionLikeMember>member).body).statements)) {
topLevelNodes.push(member);
}
addTopLevelNodes((<Block>(<MethodDeclaration>member).body).statements, topLevelNodes);
}
}
}
break;
case SyntaxKind.EnumDeclaration:
case SyntaxKind.InterfaceDeclaration:
topLevelNodes.push(node);
@ -176,29 +196,46 @@ namespace ts.NavigationBar {
}
}
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration) {
function hasNamedFunctionDeclarations(nodes: NodeArray<Statement>): boolean {
for (let s of nodes) {
if (s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text)) {
return true;
}
}
return false;
}
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration): boolean {
if (functionDeclaration.kind === SyntaxKind.FunctionDeclaration) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
// A function declaration is 'top level' if it contains any function declarations
// within it.
if (functionDeclaration.body && functionDeclaration.body.kind === SyntaxKind.Block) {
// Proper function declarations can only have identifier names
if (forEach((<Block>functionDeclaration.body).statements,
s => s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text))) {
if (hasNamedFunctionDeclarations((<Block>functionDeclaration.body).statements)) {
return true;
}
// Or if it is not parented by another function. i.e all functions
// at module scope are 'top level'.
// Or if it is not parented by another function. I.e all functions at module scope are 'top level'.
if (!isFunctionBlock(functionDeclaration.parent)) {
return true;
}
// Or if it is nested inside class methods and constructors.
else {
// We have made sure that a grand parent node exists with 'isFunctionBlock()' above.
const grandParentKind = functionDeclaration.parent.parent.kind;
if (grandParentKind === SyntaxKind.MethodDeclaration ||
grandParentKind === SyntaxKind.Constructor) {
return true;
}
}
}
}
return false;
}
function getItemsWorker(nodes: Node[], createItem: (n: Node) => ts.NavigationBarItem): ts.NavigationBarItem[] {
let items: ts.NavigationBarItem[] = [];
@ -370,6 +407,10 @@ namespace ts.NavigationBar {
case SyntaxKind.ClassDeclaration:
return createClassItem(<ClassDeclaration>node);
case SyntaxKind.MethodDeclaration:
case SyntaxKind.Constructor:
return createMemberFunctionLikeItem(<MethodDeclaration | ConstructorDeclaration>node);
case SyntaxKind.EnumDeclaration:
return createEnumItem(<EnumDeclaration>node);
@ -395,19 +436,19 @@ namespace ts.NavigationBar {
let result: string[] = [];
result.push(moduleDeclaration.name.text);
while (moduleDeclaration.body && moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) {
moduleDeclaration = <ModuleDeclaration>moduleDeclaration.body;
result.push(moduleDeclaration.name.text);
}
}
return result.join(".");
}
function createModuleItem(node: ModuleDeclaration): NavigationBarItem {
let moduleName = getModuleName(node);
let childItems = getItemsWorker(getChildNodes((<Block>getInnermostModule(node).body).statements), createChildItem);
return getNavigationBarItem(moduleName,
@ -418,11 +459,11 @@ namespace ts.NavigationBar {
getIndent(node));
}
function createFunctionItem(node: FunctionDeclaration) {
function createFunctionItem(node: FunctionDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
return getNavigationBarItem(!node.name ? "default": node.name.text ,
return getNavigationBarItem(!node.name ? "default": node.name.text,
ts.ScriptElementKind.functionElement,
getNodeModifiers(node),
[getNodeSpan(node)],
@ -433,6 +474,31 @@ namespace ts.NavigationBar {
return undefined;
}
function createMemberFunctionLikeItem(node: MethodDeclaration | ConstructorDeclaration): ts.NavigationBarItem {
if (node.body && node.body.kind === SyntaxKind.Block) {
let childItems = getItemsWorker(sortNodes((<Block>node.body).statements), createChildItem);
let scriptElementKind: string;
let memberFunctionName: string;
if (node.kind === SyntaxKind.MethodDeclaration) {
memberFunctionName = getPropertyNameForPropertyNameNode(node.name);
scriptElementKind = ts.ScriptElementKind.memberFunctionElement;
}
else {
memberFunctionName = "constructor";
scriptElementKind = ts.ScriptElementKind.constructorImplementationElement;
}
return getNavigationBarItem(memberFunctionName,
scriptElementKind,
getNodeModifiers(node),
[getNodeSpan(node)],
childItems,
getIndent(node));
}
return undefined;
}
function createSourceFileItem(node: SourceFile): ts.NavigationBarItem {
let childItems = getItemsWorker(getChildNodes(node.statements), createChildItem);
@ -534,4 +600,206 @@ namespace ts.NavigationBar {
return getTextOfNodeFromSourceText(sourceFile.text, node);
}
}
}
export function getJsNavigationBarItems(sourceFile: SourceFile, compilerOptions: CompilerOptions): NavigationBarItem[] {
const anonFnText = "<function>";
const anonClassText = "<class>";
let indent = 0;
let rootName = isExternalModule(sourceFile) ?
"\"" + escapeString(getBaseFileName(removeFileExtension(normalizePath(sourceFile.fileName)))) + "\""
: "<global>";
let sourceFileItem = getNavBarItem(rootName, ScriptElementKind.moduleElement, [getNodeSpan(sourceFile)]);
let topItem = sourceFileItem;
// Walk the whole file, because we want to also find function expressions - which may be in variable initializer,
// call arguments, expressions, etc...
forEachChild(sourceFile, visitNode);
function visitNode(node: Node) {
const newItem = createNavBarItem(node);
if (newItem) {
topItem.childItems.push(newItem);
}
// Add a level if traversing into a container
if (newItem && (isFunctionLike(node) || isClassLike(node))) {
const lastTop = topItem;
indent++;
topItem = newItem;
forEachChild(node, visitNode);
topItem = lastTop;
indent--;
// If the last item added was an anonymous function expression, and it had no children, discard it.
if (newItem && newItem.text === anonFnText && newItem.childItems.length === 0) {
topItem.childItems.pop();
}
}
else {
forEachChild(node, visitNode);
}
}
function createNavBarItem(node: Node) : NavigationBarItem {
switch (node.kind) {
case SyntaxKind.VariableDeclaration:
// Only add to the navbar if at the top-level of the file
// Note: "const" and "let" are also SyntaxKind.VariableDeclarations
if(node.parent/*VariableDeclarationList*/.parent/*VariableStatement*/
.parent/*SourceFile*/.kind !== SyntaxKind.SourceFile) {
return undefined;
}
// If it is initialized with a function expression, handle it when we reach the function expression node
const varDecl = node as VariableDeclaration;
if (varDecl.initializer && (varDecl.initializer.kind === SyntaxKind.FunctionExpression ||
varDecl.initializer.kind === SyntaxKind.ArrowFunction ||
varDecl.initializer.kind === SyntaxKind.ClassExpression)) {
return undefined;
}
// Fall through
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.Constructor:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
// "export default function().." looks just like a regular function/class declaration, except with the 'default' flag
const name = node.flags && (node.flags & NodeFlags.Default) && !(node as (Declaration)).name ? "default" :
node.kind === SyntaxKind.Constructor ? "constructor" :
declarationNameToString((node as (Declaration)).name);
return getNavBarItem(name, getScriptKindForElementKind(node.kind), [getNodeSpan(node)]);
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
case SyntaxKind.ClassExpression:
return getDefineModuleItem(node) || getFunctionOrClassExpressionItem(node);
case SyntaxKind.MethodDeclaration:
const methodDecl = node as MethodDeclaration;
return getNavBarItem(declarationNameToString(methodDecl.name),
ScriptElementKind.memberFunctionElement,
[getNodeSpan(node)]);
case SyntaxKind.ExportAssignment:
// e.g. "export default <expr>"
return getNavBarItem("default", ScriptElementKind.variableElement, [getNodeSpan(node)]);
case SyntaxKind.ImportClause: // e.g. 'def' in: import def from 'mod' (in ImportDeclaration)
if (!(node as ImportClause).name) {
// No default import (this node is still a parent of named & namespace imports, which are handled below)
return undefined;
}
// fall through
case SyntaxKind.ImportSpecifier: // e.g. 'id' in: import {id} from 'mod' (in NamedImports, in ImportClause)
case SyntaxKind.NamespaceImport: // e.g. '* as ns' in: import * as ns from 'mod' (in ImportClause)
case SyntaxKind.ExportSpecifier: // e.g. 'a' or 'b' in: export {a, foo as b} from 'mod'
// Export specifiers are only interesting if they are reexports from another module, or renamed, else they are already globals
if (node.kind === SyntaxKind.ExportSpecifier) {
if (!(node.parent.parent as ExportDeclaration).moduleSpecifier && !(node as ExportSpecifier).propertyName) {
return undefined;
}
}
const decl = node as (ImportSpecifier | ImportClause | NamespaceImport | ExportSpecifier);
if (!decl.name) {
return undefined;
}
const declName = declarationNameToString(decl.name);
return getNavBarItem(declName, ScriptElementKind.constElement, [getNodeSpan(node)]);
default:
return undefined;
}
}
function getNavBarItem(text: string, kind: string, spans: TextSpan[], kindModifiers = ScriptElementKindModifier.none): NavigationBarItem {
return {
text, kind, kindModifiers, spans, childItems: [], indent, bolded: false, grayed: false
}
}
function getDefineModuleItem(node: Node): NavigationBarItem {
if (node.kind !== SyntaxKind.FunctionExpression && node.kind !== SyntaxKind.ArrowFunction) {
return undefined;
}
// No match if this is not a call expression to an identifier named 'define'
if (node.parent.kind !== SyntaxKind.CallExpression) {
return undefined;
}
const callExpr = node.parent as CallExpression;
if (callExpr.expression.kind !== SyntaxKind.Identifier || callExpr.expression.getText() !== 'define') {
return undefined;
}
// Return a module of either the given text in the first argument, or of the source file path
let defaultName = node.getSourceFile().fileName;
if (callExpr.arguments[0].kind === SyntaxKind.StringLiteral) {
defaultName = ((callExpr.arguments[0]) as StringLiteral).text;
}
return getNavBarItem(defaultName, ScriptElementKind.moduleElement, [getNodeSpan(node.parent)]);
}
function getFunctionOrClassExpressionItem(node: Node): NavigationBarItem {
if (node.kind !== SyntaxKind.FunctionExpression &&
node.kind !== SyntaxKind.ArrowFunction &&
node.kind !== SyntaxKind.ClassExpression) {
return undefined;
}
const fnExpr = node as FunctionExpression | ArrowFunction | ClassExpression;
let fnName: string;
if (fnExpr.name && getFullWidth(fnExpr.name) > 0) {
// The expression has an identifier, so use that as the name
fnName = declarationNameToString(fnExpr.name);
}
else {
// See if it is a var initializer. If so, use the var name.
if (fnExpr.parent.kind === SyntaxKind.VariableDeclaration) {
fnName = declarationNameToString((fnExpr.parent as VariableDeclaration).name);
}
// See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
else if (fnExpr.parent.kind === SyntaxKind.BinaryExpression &&
(fnExpr.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
fnName = (fnExpr.parent as BinaryExpression).left.getText();
if (fnName.length > 20) {
fnName = fnName.substring(0, 17) + "...";
}
}
// See if it is a property assignment, and if so use the property name
else if (fnExpr.parent.kind === SyntaxKind.PropertyAssignment &&
(fnExpr.parent as PropertyAssignment).name) {
fnName = (fnExpr.parent as PropertyAssignment).name.getText();
}
else {
fnName = node.kind === SyntaxKind.ClassExpression ? anonClassText : anonFnText;
}
}
const scriptKind = node.kind === SyntaxKind.ClassExpression ? ScriptElementKind.classElement : ScriptElementKind.functionElement;
return getNavBarItem(fnName, scriptKind, [getNodeSpan(node)]);
}
function getNodeSpan(node: Node) {
return node.kind === SyntaxKind.SourceFile
? createTextSpanFromBounds(node.getFullStart(), node.getEnd())
: createTextSpanFromBounds(node.getStart(), node.getEnd());
}
function getScriptKindForElementKind(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.VariableDeclaration:
return ScriptElementKind.variableElement;
case SyntaxKind.FunctionDeclaration:
return ScriptElementKind.functionElement;
case SyntaxKind.ClassDeclaration:
return ScriptElementKind.classElement;
case SyntaxKind.Constructor:
return ScriptElementKind.constructorImplementationElement;
case SyntaxKind.GetAccessor:
return ScriptElementKind.memberGetAccessorElement;
case SyntaxKind.SetAccessor:
return ScriptElementKind.memberSetAccessorElement;
default:
return "unknown";
}
}
return sourceFileItem.childItems;
}
}

View File

@ -7,12 +7,13 @@
/// <reference path='patternMatcher.ts' />
/// <reference path='signatureHelp.ts' />
/// <reference path='utilities.ts' />
/// <reference path='jsTyping.ts' />
/// <reference path='formatting\formatting.ts' />
/// <reference path='formatting\smartIndenter.ts' />
namespace ts {
/** The version of the language service API */
export const servicesVersion = "0.4";
export const servicesVersion = "0.5";
export interface Node {
getSourceFile(): SourceFile;
@ -124,6 +125,7 @@ namespace ts {
}
export interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@ -740,6 +742,7 @@ namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType: Type;
resolvedReturnType: Type;
minArgumentCount: number;
hasRestParameter: boolean;
@ -791,6 +794,7 @@ namespace ts {
public amdDependencies: { name: string; path: string }[];
public moduleName: string;
public referencedFiles: FileReference[];
public typeReferenceDirectives: FileReference[];
public syntacticDiagnostics: Diagnostic[];
public referenceDiagnostics: Diagnostic[];
@ -812,6 +816,7 @@ namespace ts {
public identifiers: Map<string>;
public nameTable: Map<number>;
public resolvedModules: Map<ResolvedModule>;
public resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
public imports: LiteralExpression[];
public moduleAugmentations: LiteralExpression[];
private namedDeclarations: Map<Declaration[]>;
@ -1038,6 +1043,7 @@ namespace ts {
* host specific questions using 'getScriptSnapshot'.
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
@ -1107,11 +1113,13 @@ namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
/* @internal */ getNonBoundSourceFile(fileName: string): SourceFile;
dispose(): void;
}
@ -1751,14 +1759,13 @@ namespace ts {
private createEntry(fileName: string, path: Path) {
let entry: HostFileInformation;
const scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : ScriptKind.Unknown;
const scriptSnapshot = this.host.getScriptSnapshot(fileName);
if (scriptSnapshot) {
entry = {
hostFileName: fileName,
version: this.host.getScriptVersion(fileName),
scriptSnapshot: scriptSnapshot,
scriptKind: scriptKind ? scriptKind : getScriptKindFromFileName(fileName)
scriptKind: getScriptKind(fileName, this.host)
};
}
@ -1824,7 +1831,7 @@ namespace ts {
throw new Error("Could not find file: '" + fileName + "'.");
}
const scriptKind = this.host.getScriptKind ? this.host.getScriptKind(fileName) : ScriptKind.Unknown;
const scriptKind = getScriptKind(fileName, this.host);
const version = this.host.getScriptVersion(fileName);
let sourceFile: SourceFile;
@ -1883,7 +1890,7 @@ namespace ts {
options.isolatedModules = true;
// transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
// transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths.
options.suppressOutputPathCheck = true;
// Filename can be non-ts file.
@ -2146,9 +2153,25 @@ namespace ts {
export function preProcessFile(sourceText: string, readImportFiles = true, detectJavaScriptImports = false): PreProcessedFileInfo {
const referencedFiles: FileReference[] = [];
const typeReferenceDirectives: FileReference[] = [];
const importedFiles: FileReference[] = [];
let ambientExternalModules: string[];
let ambientExternalModules: { ref: FileReference, depth: number }[];
let isNoDefaultLib = false;
let braceNesting = 0;
// assume that text represent an external module if it contains at least one top level import/export
// ambient modules that are found inside external modules are interpreted as module augmentations
let externalModule = false;
function nextToken() {
const token = scanner.scan();
if (token === SyntaxKind.OpenBraceToken) {
braceNesting++;
}
else if (token === SyntaxKind.CloseBraceToken) {
braceNesting--;
}
return token;
}
function processTripleSlashDirectives(): void {
const commentRanges = getLeadingCommentRanges(sourceText, 0);
@ -2159,27 +2182,43 @@ namespace ts {
isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
const fileReference = referencePathMatchResult.fileReference;
if (fileReference) {
referencedFiles.push(fileReference);
const collection = referencePathMatchResult.isTypeReferenceDirective
? typeReferenceDirectives
: referencedFiles;
collection.push(fileReference);
}
}
});
}
function getFileReference() {
const file = scanner.getTokenValue();
const pos = scanner.getTokenPos();
return {
fileName: file,
pos: pos,
end: pos + file.length
};
}
function recordAmbientExternalModule(): void {
if (!ambientExternalModules) {
ambientExternalModules = [];
}
ambientExternalModules.push(scanner.getTokenValue());
ambientExternalModules.push({ ref: getFileReference(), depth: braceNesting });
}
function recordModuleName() {
const importPath = scanner.getTokenValue();
const pos = scanner.getTokenPos();
importedFiles.push({
fileName: importPath,
pos: pos,
end: pos + importPath.length
});
importedFiles.push(getFileReference());
markAsExternalModuleIfTopLevel();
}
function markAsExternalModuleIfTopLevel() {
if (braceNesting === 0) {
externalModule = true;
}
}
/**
@ -2189,9 +2228,9 @@ namespace ts {
let token = scanner.getToken();
if (token === SyntaxKind.DeclareKeyword) {
// declare module "mod"
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.ModuleKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
recordAmbientExternalModule();
}
@ -2208,7 +2247,8 @@ namespace ts {
function tryConsumeImport(): boolean {
let token = scanner.getToken();
if (token === SyntaxKind.ImportKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// import "mod";
recordModuleName();
@ -2216,9 +2256,9 @@ namespace ts {
}
else {
if (token === SyntaxKind.Identifier || isKeyword(token)) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.FromKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// import d from "mod";
recordModuleName();
@ -2232,7 +2272,7 @@ namespace ts {
}
else if (token === SyntaxKind.CommaToken) {
// consume comma and keep going
token = scanner.scan();
token = nextToken();
}
else {
// unknown syntax
@ -2241,17 +2281,17 @@ namespace ts {
}
if (token === SyntaxKind.OpenBraceToken) {
token = scanner.scan();
token = nextToken();
// consume "{ a as B, c, d as D}" clauses
// make sure that it stops on EOF
while (token !== SyntaxKind.CloseBraceToken && token !== SyntaxKind.EndOfFileToken) {
token = scanner.scan();
token = nextToken();
}
if (token === SyntaxKind.CloseBraceToken) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.FromKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// import {a as A} from "mod";
// import d, {a, b as B} from "mod"
@ -2261,13 +2301,13 @@ namespace ts {
}
}
else if (token === SyntaxKind.AsteriskToken) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.AsKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.Identifier || isKeyword(token)) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.FromKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// import * as NS from "mod"
// import d, * as NS from "mod"
@ -2288,19 +2328,20 @@ namespace ts {
function tryConsumeExport(): boolean {
let token = scanner.getToken();
if (token === SyntaxKind.ExportKeyword) {
token = scanner.scan();
markAsExternalModuleIfTopLevel();
token = nextToken();
if (token === SyntaxKind.OpenBraceToken) {
token = scanner.scan();
token = nextToken();
// consume "{ a as B, c, d as D}" clauses
// make sure it stops on EOF
while (token !== SyntaxKind.CloseBraceToken && token !== SyntaxKind.EndOfFileToken) {
token = scanner.scan();
token = nextToken();
}
if (token === SyntaxKind.CloseBraceToken) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.FromKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// export {a as A} from "mod";
// export {a, b as B} from "mod"
@ -2310,9 +2351,9 @@ namespace ts {
}
}
else if (token === SyntaxKind.AsteriskToken) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.FromKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// export * from "mod"
recordModuleName();
@ -2320,9 +2361,9 @@ namespace ts {
}
}
else if (token === SyntaxKind.ImportKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.Identifier || isKeyword(token)) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.EqualsToken) {
if (tryConsumeRequireCall(/*skipCurrentToken*/ true)) {
return true;
@ -2338,11 +2379,11 @@ namespace ts {
}
function tryConsumeRequireCall(skipCurrentToken: boolean): boolean {
let token = skipCurrentToken ? scanner.scan() : scanner.getToken();
let token = skipCurrentToken ? nextToken() : scanner.getToken();
if (token === SyntaxKind.RequireKeyword) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.OpenParenToken) {
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// require("mod");
recordModuleName();
@ -2356,17 +2397,17 @@ namespace ts {
function tryConsumeDefine(): boolean {
let token = scanner.getToken();
if (token === SyntaxKind.Identifier && scanner.getTokenValue() === "define") {
token = scanner.scan();
token = nextToken();
if (token !== SyntaxKind.OpenParenToken) {
return true;
}
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.StringLiteral) {
// looks like define ("modname", ... - skip string literal and comma
token = scanner.scan();
token = nextToken();
if (token === SyntaxKind.CommaToken) {
token = scanner.scan();
token = nextToken();
}
else {
// unexpected token
@ -2380,7 +2421,7 @@ namespace ts {
}
// skip open bracket
token = scanner.scan();
token = nextToken();
let i = 0;
// scan until ']' or EOF
while (token !== SyntaxKind.CloseBracketToken && token !== SyntaxKind.EndOfFileToken) {
@ -2390,7 +2431,7 @@ namespace ts {
i++;
}
token = scanner.scan();
token = nextToken();
}
return true;
@ -2400,7 +2441,7 @@ namespace ts {
function processImports(): void {
scanner.setText(sourceText);
scanner.scan();
nextToken();
// Look for:
// import "mod";
// import d from "mod"
@ -2427,7 +2468,7 @@ namespace ts {
continue;
}
else {
scanner.scan();
nextToken();
}
}
@ -2438,7 +2479,34 @@ namespace ts {
processImports();
}
processTripleSlashDirectives();
return { referencedFiles, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules };
if (externalModule) {
// for external modules module all nested ambient modules are augmentations
if (ambientExternalModules) {
// move all detected ambient modules to imported files since they need to be resolved
for (const decl of ambientExternalModules) {
importedFiles.push(decl.ref);
}
}
return { referencedFiles, typeReferenceDirectives, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
}
else {
// for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
let ambientModuleNames: string[];
if (ambientExternalModules) {
for (const decl of ambientExternalModules) {
if (decl.depth === 0) {
if (!ambientModuleNames) {
ambientModuleNames = [];
}
ambientModuleNames.push(decl.ref.fileName);
}
else {
importedFiles.push(decl.ref);
}
}
}
return { referencedFiles, typeReferenceDirectives, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
}
}
/// Helpers
@ -2774,7 +2842,7 @@ namespace ts {
getCurrentDirectory: () => currentDirectory,
fileExists: (fileName): boolean => {
// stub missing host functionality
Debug.assert(!host.resolveModuleNames);
Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives);
return hostCache.getOrCreateEntry(fileName) !== undefined;
},
readFile: (fileName): string => {
@ -2783,7 +2851,7 @@ namespace ts {
return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength());
},
directoryExists: directoryName => {
Debug.assert(!host.resolveModuleNames);
Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives);
return directoryProbablyExists(directoryName, host);
}
};
@ -2794,6 +2862,11 @@ namespace ts {
if (host.resolveModuleNames) {
compilerHost.resolveModuleNames = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile);
}
if (host.resolveTypeReferenceDirectives) {
compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile) => {
return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile);
};
}
const newProgram = createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program);
@ -3448,7 +3521,18 @@ namespace ts {
// We don't want to complete using the type acquired by the shape
// of the binding pattern; we are only interested in types acquired
// through type declaration or inference.
if (rootDeclaration.initializer || rootDeclaration.type) {
// Also proceed if rootDeclaration is parameter and if its containing function expression\arrow function is contextually typed -
// type of parameter will flow in from the contextual type of the function
let canGetType = !!(rootDeclaration.initializer || rootDeclaration.type);
if (!canGetType && rootDeclaration.kind === SyntaxKind.Parameter) {
if (isExpression(rootDeclaration.parent)) {
canGetType = !!typeChecker.getContextualType(<Expression>rootDeclaration.parent);
}
else if (rootDeclaration.parent.kind === SyntaxKind.MethodDeclaration || rootDeclaration.parent.kind === SyntaxKind.SetAccessor) {
canGetType = isExpression(rootDeclaration.parent.parent) && !!typeChecker.getContextualType(<Expression>rootDeclaration.parent.parent);
}
}
if (canGetType) {
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
@ -3752,10 +3836,10 @@ namespace ts {
}
if (isEmpty(existingImportsOrExports)) {
return exportsOfModule;
return filter(exportsOfModule, e => e.name !== "default");
}
return filter(exportsOfModule, e => !lookUp(existingImportsOrExports, e.name));
return filter(exportsOfModule, e => e.name !== "default" && !lookUp(existingImportsOrExports, e.name));
}
/**
@ -4042,6 +4126,9 @@ namespace ts {
if (typeChecker.isArgumentsSymbol(symbol)) {
return ScriptElementKind.localVariableElement;
}
if (location.kind === SyntaxKind.ThisKeyword && isExpression(location)) {
return ScriptElementKind.parameterElement;
}
if (flags & SymbolFlags.Variable) {
if (isFirstDeclarationOfSymbolParameter(symbol)) {
return ScriptElementKind.parameterElement;
@ -4104,6 +4191,7 @@ namespace ts {
const symbolFlags = symbol.flags;
let symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location);
let hasAddedSymbolInfo: boolean;
const isThisExpression: boolean = location.kind === SyntaxKind.ThisKeyword && isExpression(location);
let type: Type;
// Class at constructor site need to be shown as constructor apart from property,method, vars
@ -4114,7 +4202,7 @@ namespace ts {
}
let signature: Signature;
type = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location);
if (type) {
if (location.parent && location.parent.kind === SyntaxKind.PropertyAccessExpression) {
const right = (<PropertyAccessExpression>location.parent).name;
@ -4225,7 +4313,7 @@ namespace ts {
}
}
}
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo) {
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo && !isThisExpression) {
if (getDeclarationOfKind(symbol, SyntaxKind.ClassExpression)) {
// Special case for class expressions because we would like to indicate that
// the class name is local to the class body (similar to function expression)
@ -4367,11 +4455,19 @@ namespace ts {
if (!hasAddedSymbolInfo) {
if (symbolKind !== ScriptElementKind.unknown) {
if (type) {
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
if (isThisExpression) {
addNewLineIfDisplayPartsExist();
displayParts.push(keywordPart(SyntaxKind.ThisKeyword));
}
else {
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
}
// For properties, variables and local vars: show the type
if (symbolKind === ScriptElementKind.memberVariableElement ||
symbolFlags & SymbolFlags.Variable ||
symbolKind === ScriptElementKind.localVariableElement) {
symbolKind === ScriptElementKind.localVariableElement ||
isThisExpression) {
displayParts.push(punctuationPart(SyntaxKind.ColonToken));
displayParts.push(spacePart());
// If the type is type parameter, format it specially
@ -4603,6 +4699,26 @@ namespace ts {
}
}
function findReferenceInPosition(refs: FileReference[], pos: number): FileReference {
for (const ref of refs) {
if (ref.pos <= pos && pos < ref.end) {
return ref;
}
}
return undefined;
}
function getDefinitionInfoForFileReference(name: string, targetFileName: string): DefinitionInfo {
return {
fileName: targetFileName,
textSpan: createTextSpanFromBounds(0, 0),
kind: ScriptElementKind.scriptElement,
name: name,
containerName: undefined,
containerKind: undefined
};
}
/// Goto definition
function getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
synchronizeHostData();
@ -4622,18 +4738,20 @@ namespace ts {
}
/// Triple slash reference comments
const comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined);
const comment = findReferenceInPosition(sourceFile.referencedFiles, position);
if (comment) {
const referenceFile = tryResolveScriptReference(program, sourceFile, comment);
if (referenceFile) {
return [{
fileName: referenceFile.fileName,
textSpan: createTextSpanFromBounds(0, 0),
kind: ScriptElementKind.scriptElement,
name: comment.fileName,
containerName: undefined,
containerKind: undefined
}];
return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)];
}
return undefined;
}
// Type reference directives
const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
const referenceFile = lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName);
if (referenceFile && referenceFile.resolvedFileName) {
return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
}
return undefined;
}
@ -5544,8 +5662,51 @@ namespace ts {
};
}
function isImportSpecifierSymbol(symbol: Symbol) {
return (symbol.flags & SymbolFlags.Alias) && !!getDeclarationOfKind(symbol, SyntaxKind.ImportSpecifier);
function getAliasSymbolForPropertyNameSymbol(symbol: Symbol, location: Node): Symbol {
if (symbol.flags & SymbolFlags.Alias) {
// Default import get alias
const defaultImport = getDeclarationOfKind(symbol, SyntaxKind.ImportClause);
if (defaultImport) {
return typeChecker.getAliasedSymbol(symbol);
}
const importOrExportSpecifier = <ImportOrExportSpecifier>forEach(symbol.declarations,
declaration => (declaration.kind === SyntaxKind.ImportSpecifier ||
declaration.kind === SyntaxKind.ExportSpecifier) ? declaration : undefined);
if (importOrExportSpecifier &&
// export { a }
(!importOrExportSpecifier.propertyName ||
// export {a as class } where a is location
importOrExportSpecifier.propertyName === location)) {
// If Import specifier -> get alias
// else Export specifier -> get local target
return importOrExportSpecifier.kind === SyntaxKind.ImportSpecifier ?
typeChecker.getAliasedSymbol(symbol) :
typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier);
}
}
return undefined;
}
function getPropertySymbolOfDestructuringAssignment(location: Node) {
return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) &&
typeChecker.getPropertySymbolOfDestructuringAssignment(<Identifier>location);
}
function isObjectBindingPatternElementWithoutPropertyName(symbol: Symbol) {
const bindingElement = <BindingElement>getDeclarationOfKind(symbol, SyntaxKind.BindingElement);
return bindingElement &&
bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern &&
!bindingElement.propertyName;
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol) {
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
const bindingElement = <BindingElement>getDeclarationOfKind(symbol, SyntaxKind.BindingElement);
const typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent);
return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, (<Identifier>bindingElement.name).text);
}
return undefined;
}
function getInternedName(symbol: Symbol, location: Node, declarations: Declaration[]): string {
@ -5593,6 +5754,12 @@ namespace ts {
return undefined;
}
// If symbol is of object binding pattern element without property name we would want to
// look for property too and that could be anywhere
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
return undefined;
}
// if this symbol is visible from its parent container, e.g. exported, then bail out
// if symbol correspond to the union property - bail out
if (symbol.parent || (symbol.flags & SymbolFlags.SyntheticProperty)) {
@ -5988,18 +6155,30 @@ namespace ts {
// The search set contains at least the current symbol
let result = [symbol];
// If the symbol is an alias, add what it aliases to the list
if (isImportSpecifierSymbol(symbol)) {
result.push(typeChecker.getAliasedSymbol(symbol));
// If the location is name of property symbol from object literal destructuring pattern
// Search the property symbol
// for ( { property: p2 } of elems) { }
if (isNameOfPropertyAssignment(location) && location.parent.kind !== SyntaxKind.ShorthandPropertyAssignment) {
const propertySymbol = getPropertySymbolOfDestructuringAssignment(location);
if (propertySymbol) {
result.push(propertySymbol);
}
}
// For export specifiers, the exported name can be referring to a local symbol, e.g.:
// If the symbol is an alias, add what it aliases to the list
// import {a} from "mod";
// export {a as somethingElse}
// We want the *local* declaration of 'a' as declared in the import,
// *not* as declared within "mod" (or farther)
if (location.parent.kind === SyntaxKind.ExportSpecifier) {
result.push(typeChecker.getExportSpecifierLocalTargetSymbol(<ExportSpecifier>location.parent));
// export {a}
// If the symbol is an alias to default declaration, add what it aliases to the list
// declare "mod" { export default class B { } }
// import B from "mod";
//// For export specifiers, the exported name can be referring to a local symbol, e.g.:
//// import {a} from "mod";
//// export {a as somethingElse}
//// We want the *local* declaration of 'a' as declared in the import,
//// *not* as declared within "mod" (or farther)
const aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location);
if (aliasSymbol) {
result = result.concat(populateSearchSymbolSet(aliasSymbol, location));
}
// If the location is in a context sensitive location (i.e. in an object literal) try
@ -6036,6 +6215,13 @@ namespace ts {
result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(<ParameterDeclaration>symbol.valueDeclaration, symbol.name));
}
// If this is symbol of binding element without propertyName declaration in Object binding pattern
// Include the property in the search
const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol);
if (bindingElementPropertySymbol) {
result.push(bindingElementPropertySymbol);
}
// If this is a union property, add all the symbols from all its source symbols in all unioned types.
// If the symbol is an instantiation from a another symbol (e.g. widened symbol) , add the root the list
forEach(typeChecker.getRootSymbols(symbol), rootSymbol => {
@ -6083,7 +6269,7 @@ namespace ts {
if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) {
forEach(symbol.getDeclarations(), declaration => {
if (declaration.kind === SyntaxKind.ClassDeclaration) {
if (isClassLike(declaration)) {
getPropertySymbolFromTypeReference(getClassExtendsHeritageClauseElement(<ClassDeclaration>declaration));
forEach(getClassImplementsHeritageClauseElements(<ClassDeclaration>declaration), getPropertySymbolFromTypeReference);
}
@ -6100,7 +6286,7 @@ namespace ts {
if (type) {
const propertySymbol = typeChecker.getPropertyOfType(type, propertyName);
if (propertySymbol) {
result.push(propertySymbol);
result.push(...typeChecker.getRootSymbols(propertySymbol));
}
// Visit the typeReference as well to see if it directly or indirectly use that property
@ -6117,32 +6303,40 @@ namespace ts {
}
// If the reference symbol is an alias, check if what it is aliasing is one of the search
// symbols.
if (isImportSpecifierSymbol(referenceSymbol)) {
const aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol);
if (searchSymbols.indexOf(aliasedSymbol) >= 0) {
return aliasedSymbol;
}
}
// For export specifiers, it can be a local symbol, e.g.
// import {a} from "mod";
// export {a as somethingElse}
// We want the local target of the export (i.e. the import symbol) and not the final target (i.e. "mod".a)
if (referenceLocation.parent.kind === SyntaxKind.ExportSpecifier) {
const aliasedSymbol = typeChecker.getExportSpecifierLocalTargetSymbol(<ExportSpecifier>referenceLocation.parent);
if (searchSymbols.indexOf(aliasedSymbol) >= 0) {
return aliasedSymbol;
}
// symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness.
const aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation);
if (aliasSymbol) {
return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation);
}
// If the reference location is in an object literal, try to get the contextual type for the
// object literal, lookup the property symbol in the contextual type, and use this symbol to
// compare to our searchSymbol
if (isNameOfPropertyAssignment(referenceLocation)) {
return forEach(getPropertySymbolsFromContextualType(referenceLocation), contextualSymbol => {
const contextualSymbol = forEach(getPropertySymbolsFromContextualType(referenceLocation), contextualSymbol => {
return forEach(typeChecker.getRootSymbols(contextualSymbol), s => searchSymbols.indexOf(s) >= 0 ? s : undefined);
});
if (contextualSymbol) {
return contextualSymbol;
}
// If the reference location is the name of property from object literal destructuring pattern
// Get the property symbol from the object literal's type and look if thats the search symbol
// In below eg. get 'property' from type of elems iterating type
// for ( { property: p2 } of elems) { }
const propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation);
if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) {
return propertySymbol;
}
}
// If the reference location is the binding element and doesn't have property name
// then include the binding element in the related symbols
// let { a } : { a };
const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol);
if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) {
return bindingElementPropertySymbol;
}
// Unwrap symbols to get to the root (e.g. transient symbols as a result of widening)
@ -6461,7 +6655,7 @@ namespace ts {
}
/// Syntactic features
function getSourceFile(fileName: string): SourceFile {
function getNonBoundSourceFile(fileName: string): SourceFile {
return syntaxTreeCache.getCurrentSourceFile(fileName);
}
@ -7254,6 +7448,36 @@ namespace ts {
return { newText: result, caretOffset: preamble.length };
}
function isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): boolean {
// '<' is currently not supported, figuring out if we're in a Generic Type vs. a comparison is too
// expensive to do during typing scenarios
// i.e. whether we're dealing with:
// var x = new foo<| ( with class foo<T>{} )
// or
// var y = 3 <|
if (openingBrace === CharacterCodes.lessThan) {
return false;
}
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
// Check if in a context where we don't want to perform any insertion
if (isInString(sourceFile, position) || isInComment(sourceFile, position)) {
return false;
}
if (isInsideJsxElementOrAttribute(sourceFile, position)) {
return openingBrace === CharacterCodes.openBrace;
}
if (isInTemplateString(sourceFile, position)) {
return false;
}
return true;
}
function getParametersForJsDocOwningNode(commentOwner: Node): ParameterDeclaration[] {
if (isFunctionLike(commentOwner)) {
return commentOwner.parameters;
@ -7548,8 +7772,9 @@ namespace ts {
getFormattingEditsForDocument,
getFormattingEditsAfterKeystroke,
getDocCommentTemplateAtPosition,
isValidBraceCompletionAtPostion,
getEmitOutput,
getSourceFile,
getNonBoundSourceFile,
getProgram
};
}

View File

@ -19,7 +19,7 @@
let debugObjectHost = (<any>this);
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
/* @internal */
@ -67,6 +67,7 @@ namespace ts {
useCaseSensitiveFileNames?(): boolean;
getModuleResolutionsForFile?(fileName: string): string;
getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string;
directoryExists(directoryName: string): boolean;
}
@ -78,7 +79,7 @@ namespace ts {
* @param exclude A JSON encoded string[] containing the paths to exclude
* when enumerating the directory.
*/
readDirectory(rootDir: string, extension: string, exclude?: string): string;
readDirectory(rootDir: string, extension: string, exclude?: string, depth?: number): string;
trace(s: string): void;
}
@ -220,6 +221,13 @@ namespace ts {
*/
getDocCommentTemplateAtPosition(fileName: string, position: number): string;
/**
* Returns JSON-encoded boolean to indicate whether we should support brace location
* at the current position.
* E.g. we don't want brace completion inside string-literals, comments, etc.
*/
isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): string;
getEmitOutput(fileName: string): string;
}
@ -232,6 +240,7 @@ namespace ts {
getPreProcessedFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getTSConfigFileInfo(fileName: string, sourceText: IScriptSnapshot): string;
getDefaultCompilationSettings(): string;
discoverTypings(discoverTypingsJson: string): string;
}
function logInternalError(logger: Logger, err: Error) {
@ -280,6 +289,7 @@ namespace ts {
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[];
public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[];
public directoryExists: (directoryName: string) => boolean;
constructor(private shimHost: LanguageServiceShimHost) {
@ -297,6 +307,12 @@ namespace ts {
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
this.resolveTypeReferenceDirectives = (typeDirectiveNames: string[], containingFile: string) => {
const typeDirectivesForFile = <Map<ResolvedTypeReferenceDirective>>JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile));
return map(typeDirectiveNames, name => lookUp(typeDirectivesForFile, name));
};
}
}
public log(s: string): void {
@ -422,8 +438,16 @@ namespace ts {
}
}
public readDirectory(rootDir: string, extension: string, exclude: string[]): string[] {
const encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude));
public readDirectory(rootDir: string, extension: string, exclude: string[], depth?: number): string[] {
// Wrap the API changes for 2.0 release. This try/catch
// should be removed once TypeScript 2.0 has shipped.
let encoded: string;
try {
encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude), depth);
}
catch (e) {
encoded = this.shimHost.readDirectory(rootDir, extension, JSON.stringify(exclude));
}
return JSON.parse(encoded);
}
@ -716,6 +740,13 @@ namespace ts {
);
}
public isValidBraceCompletionAtPostion(fileName: string, position: number, openingBrace: number): string {
return this.forwardJSONCall(
`isValidBraceCompletionAtPostion('${fileName}', ${position}, ${openingBrace})`,
() => this.languageService.isValidBraceCompletionAtPostion(fileName, position, openingBrace)
);
}
/// GET SMART INDENT
public getIndentationAtPosition(fileName: string, position: number, options: string /*Services.EditorOptions*/): string {
return this.forwardJSONCall(
@ -910,38 +941,49 @@ namespace ts {
});
}
public resolveTypeReferenceDirective(fileName: string, typeReferenceDirective: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => {
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host);
return {
resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
failedLookupLocations: result.failedLookupLocations
};
});
}
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
"getPreProcessedFileInfo('" + fileName + "')",
() => {
// for now treat files as JavaScript
const result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
const convertResult = {
referencedFiles: <IFileReference[]>[],
importedFiles: <IFileReference[]>[],
return {
referencedFiles: this.convertFileReferences(result.referencedFiles),
importedFiles: this.convertFileReferences(result.importedFiles),
ambientExternalModules: result.ambientExternalModules,
isLibFile: result.isLibFile
isLibFile: result.isLibFile,
typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives)
};
forEach(result.referencedFiles, refFile => {
convertResult.referencedFiles.push({
path: normalizePath(refFile.fileName),
position: refFile.pos,
length: refFile.end - refFile.pos
});
});
forEach(result.importedFiles, importedFile => {
convertResult.importedFiles.push({
path: normalizeSlashes(importedFile.fileName),
position: importedFile.pos,
length: importedFile.end - importedFile.pos
});
});
return convertResult;
});
}
private convertFileReferences(refs: FileReference[]): IFileReference[] {
if (!refs) {
return undefined;
}
const result: IFileReference[] = [];
for (const ref of refs) {
result.push({
path: normalizeSlashes(ref.fileName),
position: ref.pos,
length: ref.end - ref.pos
});
}
return result;
}
public getTSConfigFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
`getTSConfigFileInfo('${fileName}')`,
@ -953,6 +995,7 @@ namespace ts {
if (result.error) {
return {
options: {},
typingOptions: {},
files: [],
errors: [realizeDiagnostic(result.error, "\r\n")]
};
@ -963,6 +1006,7 @@ namespace ts {
return {
options: configFile.options,
typingOptions: configFile.typingOptions,
files: configFile.fileNames,
errors: realizeDiagnostics(configFile.errors, "\r\n")
};
@ -975,6 +1019,21 @@ namespace ts {
() => getDefaultCompilerOptions()
);
}
public discoverTypings(discoverTypingsJson: string): string {
const getCanonicalFileName = createGetCanonicalFileName(/*useCaseSensitivefileNames:*/ false);
return this.forwardJSONCall("discoverTypings()", () => {
const info = <DiscoverTypingsInfo>JSON.parse(discoverTypingsJson);
return ts.JsTyping.discoverTypings(
this.host,
info.fileNames,
toPath(info.projectRootPath, info.projectRootPath, getCanonicalFileName),
toPath(info.safeListPath, info.safeListPath, getCanonicalFileName),
info.packageNameToTypingLocation,
info.typingOptions,
info.compilerOptions);
});
}
}
export class TypeScriptServicesFactory implements ShimFactory {

View File

@ -559,7 +559,7 @@ namespace ts.SignatureHelp {
signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray;
suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
let parameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation));
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisType, candidateSignature.parameters, writer, invocation));
addRange(suffixDisplayParts, parameterParts);
}
else {

View File

@ -29,6 +29,7 @@
"shims.ts",
"signatureHelp.ts",
"utilities.ts",
"jsTyping.ts",
"formatting/formatting.ts",
"formatting/formattingContext.ts",
"formatting/formattingRequestKind.ts",

View File

@ -6,32 +6,6 @@ namespace ts {
list: Node;
}
export function getEndLinePosition(line: number, sourceFile: SourceFile): number {
Debug.assert(line >= 0);
let lineStarts = sourceFile.getLineStarts();
let lineIndex = line;
if (lineIndex + 1 === lineStarts.length) {
// last line - return EOF
return sourceFile.text.length - 1;
}
else {
// current line start
let start = lineStarts[lineIndex];
// take the start position of the next line -1 = it should be some line break
let pos = lineStarts[lineIndex + 1] - 1;
Debug.assert(isLineBreak(sourceFile.text.charCodeAt(pos)));
// walk backwards skipping line breaks, stop the the beginning of current line.
// i.e:
// <some text>
// $ <- end of line for this position should match the start position
while (start <= pos && isLineBreak(sourceFile.text.charCodeAt(pos))) {
pos--;
}
return pos;
}
}
export function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number {
let lineStarts = sourceFile.getLineStarts();
let line = sourceFile.getLineAndCharacterOfPosition(position).line;
@ -429,13 +403,53 @@ namespace ts {
export function isInString(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
return token && (token.kind === SyntaxKind.StringLiteral || token.kind === SyntaxKind.StringLiteralType) && position > token.getStart();
return token && (token.kind === SyntaxKind.StringLiteral || token.kind === SyntaxKind.StringLiteralType) && position > token.getStart(sourceFile);
}
export function isInComment(sourceFile: SourceFile, position: number) {
return isInCommentHelper(sourceFile, position, /*predicate*/ undefined);
}
/**
* returns true if the position is in between the open and close elements of an JSX expression.
*/
export function isInsideJsxElementOrAttribute(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
if (!token) {
return false;
}
// <div>Hello |</div>
if (token.kind === SyntaxKind.LessThanToken && token.parent.kind === SyntaxKind.JsxText) {
return true;
}
// <div> { | </div> or <div a={| </div>
if (token.kind === SyntaxKind.LessThanToken && token.parent.kind === SyntaxKind.JsxExpression) {
return true;
}
// <div> {
// |
// } < /div>
if (token && token.kind === SyntaxKind.CloseBraceToken && token.parent.kind === SyntaxKind.JsxExpression) {
return true;
}
// <div>|</div>
if (token.kind === SyntaxKind.LessThanToken && token.parent.kind === SyntaxKind.JsxClosingElement) {
return true;
}
return false;
}
export function isInTemplateString(sourceFile: SourceFile, position: number) {
let token = getTokenAtPosition(sourceFile, position);
return isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile);
}
/**
* Returns true if the cursor at position in sourceFile is within a comment that additionally
* satisfies predicate, and false otherwise.
@ -443,7 +457,7 @@ namespace ts {
export function isInCommentHelper(sourceFile: SourceFile, position: number, predicate?: (c: CommentRange) => boolean): boolean {
let token = getTokenAtPosition(sourceFile, position);
if (token && position <= token.getStart()) {
if (token && position <= token.getStart(sourceFile)) {
let commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos);
// The end marker of a single-line comment does not include the newline character.
@ -837,4 +851,22 @@ namespace ts {
};
return name;
}
export function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean {
const scriptKind = getScriptKind(fileName, host);
return forEach(scriptKinds, k => k === scriptKind);
}
export function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind {
// First check to see if the script kind was specified by the host. Chances are the host
// may override the default script kind for the file extension.
let scriptKind: ScriptKind;
if (host && host.getScriptKind) {
scriptKind = host.getScriptKind(fileName);
}
if (!scriptKind || scriptKind === ScriptKind.Unknown) {
scriptKind = getScriptKindFromFileName(fileName);
}
return ensureScriptKind(fileName, scriptKind);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -7,28 +7,28 @@ class Ship {
>Ship : Symbol(Ship, Decl(2dArrays.ts, 1, 1))
isSunk: boolean;
>isSunk : Symbol(isSunk, Decl(2dArrays.ts, 3, 12))
>isSunk : Symbol(Ship.isSunk, Decl(2dArrays.ts, 3, 12))
}
class Board {
>Board : Symbol(Board, Decl(2dArrays.ts, 5, 1))
ships: Ship[];
>ships : Symbol(ships, Decl(2dArrays.ts, 7, 13))
>ships : Symbol(Board.ships, Decl(2dArrays.ts, 7, 13))
>Ship : Symbol(Ship, Decl(2dArrays.ts, 1, 1))
cells: Cell[];
>cells : Symbol(cells, Decl(2dArrays.ts, 8, 18))
>cells : Symbol(Board.cells, Decl(2dArrays.ts, 8, 18))
>Cell : Symbol(Cell, Decl(2dArrays.ts, 0, 0))
private allShipsSunk() {
>allShipsSunk : Symbol(allShipsSunk, Decl(2dArrays.ts, 9, 18))
>allShipsSunk : Symbol(Board.allShipsSunk, Decl(2dArrays.ts, 9, 18))
return this.ships.every(function (val) { return val.isSunk; });
>this.ships.every : Symbol(Array.every, Decl(lib.d.ts, --, --))
>this.ships : Symbol(ships, Decl(2dArrays.ts, 7, 13))
>this.ships : Symbol(Board.ships, Decl(2dArrays.ts, 7, 13))
>this : Symbol(Board, Decl(2dArrays.ts, 5, 1))
>ships : Symbol(ships, Decl(2dArrays.ts, 7, 13))
>ships : Symbol(Board.ships, Decl(2dArrays.ts, 7, 13))
>every : Symbol(Array.every, Decl(lib.d.ts, --, --))
>val : Symbol(val, Decl(2dArrays.ts, 12, 42))
>val.isSunk : Symbol(Ship.isSunk, Decl(2dArrays.ts, 3, 12))

View File

@ -0,0 +1,70 @@
//// [APISample_parseConfig.ts]
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
declare var process: any;
declare var console: any;
declare var os: any;
import ts = require("typescript");
function printError(error: ts.Diagnostic): void {
if (!error) {
return;
}
console.log(`${error.file && error.file.fileName}: ${error.messageText}`);
}
export function createProgram(rootFiles: string[], compilerOptionsJson: string): ts.Program {
const { config, error } = ts.parseConfigFileTextToJson("tsconfig.json", compilerOptionsJson)
if (error) {
printError(error);
return undefined;
}
const basePath: string = process.cwd();
const settings = ts.convertCompilerOptionsFromJson(config.config["compilerOptions"], basePath);
if (!settings.options) {
for (const err of settings.errors) {
printError(err);
}
return undefined;
}
return ts.createProgram(rootFiles, settings.options);
}
//// [APISample_parseConfig.js]
/*
* Note: This test is a public API sample. The sample sources can be found
at: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler
* Please log a "breaking change" issue for any API breaking change affecting this issue
*/
"use strict";
var ts = require("typescript");
function printError(error) {
if (!error) {
return;
}
console.log((error.file && error.file.fileName) + ": " + error.messageText);
}
function createProgram(rootFiles, compilerOptionsJson) {
var _a = ts.parseConfigFileTextToJson("tsconfig.json", compilerOptionsJson), config = _a.config, error = _a.error;
if (error) {
printError(error);
return undefined;
}
var basePath = process.cwd();
var settings = ts.convertCompilerOptionsFromJson(config.config["compilerOptions"], basePath);
if (!settings.options) {
for (var _i = 0, _b = settings.errors; _i < _b.length; _i++) {
var err = _b[_i];
printError(err);
}
return undefined;
}
return ts.createProgram(rootFiles, settings.options);
}
exports.createProgram = createProgram;

View File

@ -29,10 +29,10 @@ declare module A {
>y : Symbol(y, Decl(class.d.ts, 2, 30))
x: number;
>x : Symbol(x, Decl(class.d.ts, 2, 42))
>x : Symbol(Point.x, Decl(class.d.ts, 2, 42))
y: number;
>y : Symbol(y, Decl(class.d.ts, 3, 18))
>y : Symbol(Point.y, Decl(class.d.ts, 3, 18))
}
}

View File

@ -25,8 +25,8 @@ module A {
>Point : Symbol(Point, Decl(module.d.ts, 0, 18), Decl(classPoint.ts, 0, 10))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(classPoint.ts, 2, 20))
>y : Symbol(y, Decl(classPoint.ts, 2, 37))
>x : Symbol(Point.x, Decl(classPoint.ts, 2, 20))
>y : Symbol(Point.y, Decl(classPoint.ts, 2, 37))
}
}

View File

@ -3,8 +3,8 @@ class Point {
>Point : Symbol(Point, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 0, 0), Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 4, 1))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 1, 16))
>y : Symbol(y, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 1, 33))
>x : Symbol(Point.x, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 1, 16))
>y : Symbol(Point.y, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 1, 33))
static Origin(): Point { return { x: 0, y: 0 }; }
>Origin : Symbol(Point.Origin, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 1, 55))
@ -28,8 +28,8 @@ module A {
>Point : Symbol(Point, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 11, 10), Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 16, 5))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 13, 20))
>y : Symbol(y, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 13, 37))
>x : Symbol(Point.x, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 13, 20))
>y : Symbol(Point.y, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 13, 37))
static Origin(): Point { return { x: 0, y: 0 }; }
>Origin : Symbol(Point.Origin, Decl(ClassAndModuleThatMergeWithStaticFunctionAndNonExportedFunctionThatShareAName.ts, 13, 59))

View File

@ -3,8 +3,8 @@ class Point {
>Point : Symbol(Point, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 0, 0), Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 4, 1))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 1, 16))
>y : Symbol(y, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 1, 33))
>x : Symbol(Point.x, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 1, 16))
>y : Symbol(Point.y, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 1, 33))
static Origin: Point = { x: 0, y: 0 };
>Origin : Symbol(Point.Origin, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 1, 55))
@ -28,8 +28,8 @@ module A {
>Point : Symbol(Point, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 11, 10), Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 16, 5))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 13, 20))
>y : Symbol(y, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 13, 37))
>x : Symbol(Point.x, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 13, 20))
>y : Symbol(Point.y, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 13, 37))
static Origin: Point = { x: 0, y: 0 };
>Origin : Symbol(Point.Origin, Decl(ClassAndModuleThatMergeWithStaticVariableAndNonExportedVarThatShareAName.ts, 13, 59))

View File

@ -3,8 +3,8 @@ class C {
>C : Symbol(C, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 0, 0))
const
>const : Symbol(const, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 0, 9))
>const : Symbol(C.const, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 0, 9))
x = 10;
>x : Symbol(x, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 1, 9))
>x : Symbol(C.x, Decl(ClassDeclarationWithInvalidConstOnPropertyDeclaration2.ts, 1, 9))
}

View File

@ -14,8 +14,8 @@ module enumdule {
>Point : Symbol(Point, Decl(EnumAndModuleWithSameNameAndCommonRoot.ts, 4, 17))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(EnumAndModuleWithSameNameAndCommonRoot.ts, 7, 20))
>y : Symbol(y, Decl(EnumAndModuleWithSameNameAndCommonRoot.ts, 7, 37))
>x : Symbol(Point.x, Decl(EnumAndModuleWithSameNameAndCommonRoot.ts, 7, 20))
>y : Symbol(Point.y, Decl(EnumAndModuleWithSameNameAndCommonRoot.ts, 7, 37))
}
}

View File

@ -6,13 +6,13 @@ module A {
>Point : Symbol(Point, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 0, 10))
x: number;
>x : Symbol(x, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 2, 21))
>x : Symbol(Point.x, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 2, 21))
y: number;
>y : Symbol(y, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 3, 18))
>y : Symbol(Point.y, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 3, 18))
fromOrigin(p: Point): number;
>fromOrigin : Symbol(fromOrigin, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 4, 18))
>fromOrigin : Symbol(Point.fromOrigin, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 4, 18))
>p : Symbol(p, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 6, 19))
>Point : Symbol(Point, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 0, 10))
}
@ -22,11 +22,11 @@ module A {
>Point : Symbol(Point, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 0, 10))
constructor(public x: number, public y: number) { }
>x : Symbol(x, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 10, 20))
>y : Symbol(y, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 10, 37))
>x : Symbol(Point2d.x, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 10, 20))
>y : Symbol(Point2d.y, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 10, 37))
fromOrigin(p: Point) {
>fromOrigin : Symbol(fromOrigin, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 10, 59))
>fromOrigin : Symbol(Point2d.fromOrigin, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 10, 59))
>p : Symbol(p, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 12, 19))
>Point : Symbol(Point, Decl(ExportClassWhichExtendsInterfaceWithInaccessibleType.ts, 0, 10))

Some files were not shown because too many files have changed in this diff Show More