From 8976ac96aa5ba0dd9fb34e41cd05531aaea2eef1 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 21 Jan 2020 12:35:42 -0800 Subject: [PATCH] Update LKG. --- lib/cancellationToken.js | 8 +- lib/ja/diagnosticMessages.generated.json | 2 +- lib/lib.esnext.bigint.d.ts | 650 ++++++++++---------- lib/tsc.js | 132 ++-- lib/tsserver.js | 490 ++++++++++----- lib/tsserverlibrary.js | 490 ++++++++++----- lib/typescript.js | 468 ++++++++++---- lib/typescriptServices.js | 468 ++++++++++---- lib/typingsInstaller.js | 156 +++-- lib/zh-tw/diagnosticMessages.generated.json | 2 +- 10 files changed, 1853 insertions(+), 1013 deletions(-) diff --git a/lib/cancellationToken.js b/lib/cancellationToken.js index d63145f3fc5..12a1e5b265b 100644 --- a/lib/cancellationToken.js +++ b/lib/cancellationToken.js @@ -17,13 +17,7 @@ and limitations under the License. "use strict"; var fs = require("fs"); function pipeExists(name) { - try { - fs.statSync(name); - return true; - } - catch (e) { - return false; - } + return fs.existsSync(name); } function createCancellationToken(args) { var cancellationPipeName; diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index 751357dbc01..a05d953fe14 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -454,7 +454,7 @@ "Generic_type_0_requires_1_type_argument_s_2314": "ジェネリック型 '{0}' には {1} 個の型引数が必要です。", "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "ジェネリック型 '{0}' には、{1} 個から {2} 個までの型引数が必要です。", "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "ジェネリック型のインスタンス化は非常に深く、無限である可能性があります。", - "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "ゲッターおよびセッターで表示が許可されていません。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "ゲッターおよびセッターでの表示が許可されていません。", "Global_module_exports_may_only_appear_at_top_level_1316": "グローバル モジュールのエクスポートは最上位レベルにのみ出現可能です。", "Global_module_exports_may_only_appear_in_declaration_files_1315": "グローバル モジュールのエクスポートは宣言ファイルにのみ出現可能です。", "Global_module_exports_may_only_appear_in_module_files_1314": "グローバル モジュールのエクスポートはモジュール ファイルにのみ出現可能です。", diff --git a/lib/lib.esnext.bigint.d.ts b/lib/lib.esnext.bigint.d.ts index ba9bae6e859..50967de98fe 100644 --- a/lib/lib.esnext.bigint.d.ts +++ b/lib/lib.esnext.bigint.d.ts @@ -20,9 +20,9 @@ and limitations under the License. interface BigInt { /** - * Returns a string representation of an object. - * @param radix Specifies a radix for converting numeric values to strings. - */ + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. + */ toString(radix?: number): string; /** Returns a string representation appropriate to the host environment's current locale. */ @@ -39,27 +39,27 @@ interface BigIntConstructor { readonly prototype: BigInt; /** - * Interprets the low bits of a BigInt as a 2's-complement signed integer. - * All higher bits are discarded. - * @param bits The number of low bits to use - * @param int The BigInt whose bits to extract - */ + * Interprets the low bits of a BigInt as a 2's-complement signed integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ asIntN(bits: number, int: bigint): bigint; /** - * Interprets the low bits of a BigInt as an unsigned integer. - * All higher bits are discarded. - * @param bits The number of low bits to use - * @param int The BigInt whose bits to extract - */ + * Interprets the low bits of a BigInt as an unsigned integer. + * All higher bits are discarded. + * @param bits The number of low bits to use + * @param int The BigInt whose bits to extract + */ asUintN(bits: number, int: bigint): bigint; } declare var BigInt: BigIntConstructor; /** - * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated, an exception is raised. - */ + * A typed array of 64-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 BigInt64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -74,213 +74,213 @@ interface BigInt64Array { readonly byteOffset: number; /** - * 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. - */ + * 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): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in the array until the callbackfn returns false, - * or until the end of 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. - */ + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns false, + * or until the end of 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. + */ every(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** - * 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. - */ + * 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: bigint, start?: number, end?: number): this; /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @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. - */ + * Returns the elements of an array that meet the condition specified in a callback function. + * @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: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; /** - * 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. - */ + * 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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @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. - */ + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach 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. - */ + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach 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. + */ forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; /** - * 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. - */ + * 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: bigint, fromIndex?: number): boolean; /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ indexOf(searchElement: bigint, fromIndex?: number): number; /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ join(separator?: string): string; /** Yields each index in the array. */ keys(): IterableIterator; /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ lastIndexOf(searchElement: bigint, fromIndex?: number): number; /** The length of the array. */ readonly length: number; /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map 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. - */ + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map 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. + */ map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; /** - * 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. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ + * 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. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** - * 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. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ + * 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. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** - * Calls the specified callback function for all the elements in an array, in descending order. - * 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 reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ + * Calls the specified callback function for all the elements in an array, in descending order. + * 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 reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** - * Calls the specified callback function for all the elements in an array, in descending order. - * 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 reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ + * Calls the specified callback function for all the elements in an array, in descending order. + * 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 reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ set(array: ArrayLike, offset?: number): void; /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ slice(start?: number, end?: number): BigInt64Array; /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in the array until the callbackfn returns true, or until - * the end of 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. - */ + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in the array until the callbackfn returns true, or until + * the end of 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. + */ some(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** - * Sorts the array. - * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. - */ + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; /** - * Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): BigInt64Array; + * Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): BigInt64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(): string; @@ -308,17 +308,17 @@ interface BigInt64ArrayConstructor { readonly BYTES_PER_ELEMENT: number; /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ of(...items: bigint[]): BigInt64Array; /** - * 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. - */ + * 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: ArrayLike): BigInt64Array; from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; } @@ -326,9 +326,9 @@ interface BigInt64ArrayConstructor { declare var BigInt64Array: BigInt64ArrayConstructor; /** - * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the - * requested number of bytes could not be allocated, an exception is raised. - */ + * A typed array of 64-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 BigUint64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -343,213 +343,213 @@ interface BigUint64Array { readonly byteOffset: number; /** - * 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. - */ + * 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): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; /** - * Determines whether all the members of an array satisfy the specified test. - * @param callbackfn A function that accepts up to three arguments. The every method calls - * the callbackfn function for each element in the array until the callbackfn returns false, - * or until the end of 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. - */ + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns false, + * or until the end of 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. + */ every(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** - * 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. - */ + * 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: bigint, start?: number, end?: number): this; /** - * Returns the elements of an array that meet the condition specified in a callback function. - * @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. - */ + * Returns the elements of an array that meet the condition specified in a callback function. + * @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: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; /** - * 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. - */ + * 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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; /** - * Returns the index of the first element in the array where predicate is true, and -1 - * 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, - * findIndex immediately returns that element index. Otherwise, findIndex returns -1. - * @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. - */ + * Returns the index of the first element in the array where predicate is true, and -1 + * 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, + * findIndex immediately returns that element index. Otherwise, findIndex returns -1. + * @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: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; /** - * Performs the specified action for each element in an array. - * @param callbackfn A function that accepts up to three arguments. forEach 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. - */ + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach 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. + */ forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; /** - * 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. - */ + * 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: bigint, fromIndex?: number): boolean; /** - * Returns the index of the first occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ indexOf(searchElement: bigint, fromIndex?: number): number; /** - * Adds all the elements of an array separated by the specified separator string. - * @param separator A string used to separate one element of an array from the next in the - * resulting String. If omitted, the array elements are separated with a comma. - */ + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the + * resulting String. If omitted, the array elements are separated with a comma. + */ join(separator?: string): string; /** Yields each index in the array. */ keys(): IterableIterator; /** - * Returns the index of the last occurrence of a value in an array. - * @param searchElement The value to locate in the array. - * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the - * search starts at index 0. - */ + * Returns the index of the last occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the + * search starts at index 0. + */ lastIndexOf(searchElement: bigint, fromIndex?: number): number; /** The length of the array. */ readonly length: number; /** - * Calls a defined callback function on each element of an array, and returns an array that - * contains the results. - * @param callbackfn A function that accepts up to three arguments. The map 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. - */ + * Calls a defined callback function on each element of an array, and returns an array that + * contains the results. + * @param callbackfn A function that accepts up to three arguments. The map 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. + */ map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; /** - * 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. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ + * 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. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** - * 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. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ + * 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. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** - * Calls the specified callback function for all the elements in an array, in descending order. - * 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 reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an - * argument instead of an array value. - */ + * Calls the specified callback function for all the elements in an array, in descending order. + * 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 reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an + * argument instead of an array value. + */ reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** - * Calls the specified callback function for all the elements in an array, in descending order. - * 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 reduceRight method calls - * the callbackfn function one time for each element in the array. - * @param initialValue If initialValue is specified, it is used as the initial value to start - * the accumulation. The first call to the callbackfn function provides this value as an argument - * instead of an array value. - */ + * Calls the specified callback function for all the elements in an array, in descending order. + * 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 reduceRight method calls + * the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start + * the accumulation. The first call to the callbackfn function provides this value as an argument + * instead of an array value. + */ reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; /** - * Sets a value or an array of values. - * @param array A typed or untyped array of values to set. - * @param offset The index in the current array at which the values are to be written. - */ + * Sets a value or an array of values. + * @param array A typed or untyped array of values to set. + * @param offset The index in the current array at which the values are to be written. + */ set(array: ArrayLike, offset?: number): void; /** - * Returns a section of an array. - * @param start The beginning of the specified portion of the array. - * @param end The end of the specified portion of the array. - */ + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. + */ slice(start?: number, end?: number): BigUint64Array; /** - * Determines whether the specified callback function returns true for any element of an array. - * @param callbackfn A function that accepts up to three arguments. The some method calls the - * callbackfn function for each element in the array until the callbackfn returns true, or until - * the end of 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. - */ + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls the + * callbackfn function for each element in the array until the callbackfn returns true, or until + * the end of 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. + */ some(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** - * Sorts the array. - * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. - */ + * Sorts the array. + * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. + */ sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; /** - * Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements - * at begin, inclusive, up to end, exclusive. - * @param begin The index of the beginning of the array. - * @param end The index of the end of the array. - */ - subarray(begin?: number, end?: number): BigUint64Array; + * Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements + * at begin, inclusive, up to end, exclusive. + * @param begin The index of the beginning of the array. + * @param end The index of the end of the array. + */ + subarray(begin: number, end?: number): BigUint64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(): string; @@ -577,17 +577,17 @@ interface BigUint64ArrayConstructor { readonly BYTES_PER_ELEMENT: number; /** - * Returns a new array from a set of elements. - * @param items A set of elements to include in the new array object. - */ + * Returns a new array from a set of elements. + * @param items A set of elements to include in the new array object. + */ of(...items: bigint[]): BigUint64Array; /** - * 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. - */ + * 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: ArrayLike): BigUint64Array; from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; } @@ -596,34 +596,34 @@ declare var BigUint64Array: BigUint64ArrayConstructor; interface DataView { /** - * Gets the BigInt64 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ + * Gets the BigInt64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; /** - * Gets the BigUint64 value at the specified byte offset from the start of the view. There is - * no alignment constraint; multi-byte values may be fetched from any offset. - * @param byteOffset The place in the buffer at which the value should be retrieved. - */ + * Gets the BigUint64 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multi-byte values may be fetched from any offset. + * @param byteOffset The place in the buffer at which the value should be retrieved. + */ getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; /** - * Stores a BigInt64 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ + * Stores a BigInt64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; /** - * Stores a BigUint64 value at the specified byte offset from the start of the view. - * @param byteOffset The place in the buffer at which the value should be set. - * @param value The value to set. - * @param littleEndian If false or undefined, a big-endian value should be written, - * otherwise a little-endian value should be written. - */ + * Stores a BigUint64 value at the specified byte offset from the start of the view. + * @param byteOffset The place in the buffer at which the value should be set. + * @param value The value to set. + * @param littleEndian If false or undefined, a big-endian value should be written, + * otherwise a little-endian value should be written. + */ setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; } diff --git a/lib/tsc.js b/lib/tsc.js index 505b3f19af6..372f8322cac 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -3411,10 +3411,13 @@ var ts; } } function readFileWorker(fileName, _encoding) { - if (!fileExists(fileName)) { + var buffer; + try { + buffer = _fs.readFileSync(fileName); + } + catch (e) { return undefined; } - var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { len &= ~1; @@ -3458,21 +3461,27 @@ var ts; function getAccessibleFileSystemEntries(path) { ts.perfLogger.logEvent("ReadDir: " + (path || ".")); try { - var entries = _fs.readdirSync(path || ".").sort(); + var entries = _fs.readdirSync(path || ".", { withFileTypes: true }); var files = []; var directories = []; for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { - var entry = entries_2[_i]; + var dirent = entries_2[_i]; + var entry = typeof dirent === "string" ? dirent : dirent.name; if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); var stat = void 0; - try { - stat = _fs.statSync(name); + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + var name = ts.combinePaths(path, entry); + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } } - catch (e) { - continue; + else { + stat = dirent; } if (stat.isFile()) { files.push(entry); @@ -3481,6 +3490,8 @@ var ts; directories.push(entry); } } + files.sort(); + directories.sort(); return { files: files, directories: directories }; } catch (e) { @@ -3510,8 +3521,7 @@ var ts; return fileSystemEntryExists(path, 1); } function getDirectories(path) { - ts.perfLogger.logEvent("ReadDir: " + path); - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1); }); + return getAccessibleFileSystemEntries(path).directories.slice(); } function realpath(path) { try { @@ -4292,7 +4302,7 @@ var ts; Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), - await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), @@ -4340,14 +4350,13 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), Type_only_0_must_reference_a_type_but_1_is_a_value: diag(1361, ts.DiagnosticCategory.Error, "Type_only_0_must_reference_a_type_but_1_is_a_value_1361", "Type-only {0} must reference a type, but '{1}' is a value."), Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported: diag(1362, ts.DiagnosticCategory.Error, "Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported_1362", "Enum '{0}' cannot be used as a value because only its type has been imported."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"), Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), - Split_all_invalid_type_only_imports: diag(1377, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1377", "Split all invalid type-only imports"), + Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."), @@ -4355,7 +4364,8 @@ var ts; This_import_may_be_converted_to_a_type_only_import: diag(1372, ts.DiagnosticCategory.Suggestion, "This_import_may_be_converted_to_a_type_only_import_1372", "This import may be converted to a type-only import."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), - await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher: diag(1375, ts.DiagnosticCategory.Error, "await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnex_1375", "'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher."), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1376, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1376", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", undefined, true), @@ -5301,7 +5311,7 @@ var ts; Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), @@ -5424,10 +5434,12 @@ var ts; Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"), Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), - can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"), An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), @@ -5442,6 +5454,7 @@ var ts; A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), @@ -21067,6 +21080,7 @@ var ts; error: 2 }), affectsEmit: true, + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types }, @@ -21315,12 +21329,15 @@ var ts; { name: "experimentalDecorators", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators }, { name: "emitDecoratorMetadata", type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, @@ -21333,6 +21350,7 @@ var ts; { name: "resolveJsonModule", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, @@ -21532,6 +21550,7 @@ var ts; name: "useDefineForClassFields", type: "boolean", affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set, }, @@ -24790,7 +24809,7 @@ var ts; case 104: case 194: case 195: - return isNarrowableReference(expr); + return containsNarrowableReference(expr); case 196: return hasNarrowableArgument(expr); case 200: @@ -24807,20 +24826,22 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 || expr.kind === 104 || expr.kind === 102 || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isOptionalChain(expr); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression); + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { var argument = _a[_i]; - if (isNarrowableReference(argument)) { + if (containsNarrowableReference(argument)) { return true; } } } if (expr.expression.kind === 194 && - isNarrowableReference(expr.expression.expression)) { + containsNarrowableReference(expr.expression.expression)) { return true; } return false; @@ -24834,7 +24855,7 @@ var ts; function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 62: - return isNarrowableReference(expr.left); + return containsNarrowableReference(expr.left); case 34: case 35: case 36: @@ -24862,7 +24883,7 @@ var ts; return isNarrowableOperand(expr.right); } } - return isNarrowableReference(expr); + return containsNarrowableReference(expr); } function createBranchLabel() { return initFlowNode({ flags: 4, antecedents: undefined }); @@ -27667,6 +27688,7 @@ var ts; var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; + var arrayVariances = [1]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -27907,9 +27929,12 @@ var ts; isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule, + getSuggestionForNonexistentExport: getSuggestionForNonexistentExport, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -29266,8 +29291,11 @@ var ts; } symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default") { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + if (symbolFromModule === undefined && name.escapedText === "default") { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : @@ -37730,8 +37758,9 @@ var ts; return spread; } function isSpreadableProperty(prop) { - return !(prop.flags & (8192 | 32768 | 65536)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + (!(prop.flags & (8192 | 32768 | 65536)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 && !(prop.flags & 32768); @@ -39776,6 +39805,9 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); + if (variances === ts.emptyArray) { + return 1; + } var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -39945,6 +39977,9 @@ var ts; if (ts.getObjectFlags(source) & 4 && ts.getObjectFlags(target) & 4 && source.target === target.target && !(ts.getObjectFlags(source) & 8192 || ts.getObjectFlags(target) & 8192)) { var variances = getVariances(source.target); + if (variances === ts.emptyArray) { + return 1; + } var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -40651,7 +40686,7 @@ var ts; } function getVariances(type) { if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8) { - return ts.emptyArray; + return arrayVariances; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } @@ -43866,19 +43901,7 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768) && getFalsyFlags(flowType) & 32768) { - var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { - var funcTypeNode = type.symbol.declarations[0]; - var returnType = getReturnTypeFromAnnotation(funcTypeNode); - if (returnType && returnType.flags & 1048576) { - var unionTypes_3 = funcTypeNode.type.types; - if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 146) { - var parenedFuncType = ts.getMutableClone(funcTypeNode); - parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; - ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); - } - } - } + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType; @@ -48577,12 +48600,17 @@ var ts; if (!(node.flags & 32768)) { if (isTopLevelAwait(node)) { var sourceFile = ts.getSourceFileOfNode(node); - if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || - languageVersion < 4 || - !ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher); + if (!hasParseDiagnostics(sourceFile)) { + var span = void 0; + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4) { + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } @@ -48591,7 +48619,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); if (func && func.kind !== 162 && (ts.getFunctionFlags(func) & 2) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); @@ -79674,7 +79702,7 @@ var ts; if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } - if (program.getRootFileNames().length !== rootFileNames.length) { + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { return false; } var seenResolvedRefs; diff --git a/lib/tsserver.js b/lib/tsserver.js index e8e55b1446b..c9e6eac45e5 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -64,6 +64,17 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || @@ -77,17 +88,6 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; var ts; (function (ts) { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. @@ -1275,6 +1275,11 @@ var ts; return result; } ts.clone = clone; + /** + * Creates a new object by adding the own properties of `second`, then the own properties of `first`. + * + * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen. + */ function extend(first, second) { var result = {}; for (var id in second) { @@ -5595,10 +5600,13 @@ var ts; } } function readFileWorker(fileName, _encoding) { - if (!fileExists(fileName)) { + var buffer; + try { + buffer = _fs.readFileSync(fileName); + } + catch (e) { return undefined; } - var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, @@ -5648,23 +5656,30 @@ var ts; function getAccessibleFileSystemEntries(path) { ts.perfLogger.logEvent("ReadDir: " + (path || ".")); try { - var entries = _fs.readdirSync(path || ".").sort(); + var entries = _fs.readdirSync(path || ".", { withFileTypes: true }); var files = []; var directories = []; for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { - var entry = entries_2[_i]; + var dirent = entries_2[_i]; + // withFileTypes is not supported before Node 10.10. + var entry = typeof dirent === "string" ? dirent : dirent.name; // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); var stat = void 0; - try { - stat = _fs.statSync(name); + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + var name = ts.combinePaths(path, entry); + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } } - catch (e) { - continue; + else { + stat = dirent; } if (stat.isFile()) { files.push(entry); @@ -5673,6 +5688,8 @@ var ts; directories.push(entry); } } + files.sort(); + directories.sort(); return { files: files, directories: directories }; } catch (e) { @@ -5702,8 +5719,7 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - ts.perfLogger.logEvent("ReadDir: " + path); - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + return getAccessibleFileSystemEntries(path).directories.slice(); } function realpath(path) { try { @@ -6697,7 +6713,7 @@ var ts; Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), - await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), @@ -6745,14 +6761,13 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), Type_only_0_must_reference_a_type_but_1_is_a_value: diag(1361, ts.DiagnosticCategory.Error, "Type_only_0_must_reference_a_type_but_1_is_a_value_1361", "Type-only {0} must reference a type, but '{1}' is a value."), Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported: diag(1362, ts.DiagnosticCategory.Error, "Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported_1362", "Enum '{0}' cannot be used as a value because only its type has been imported."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"), Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), - Split_all_invalid_type_only_imports: diag(1377, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1377", "Split all invalid type-only imports"), + Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."), @@ -6760,7 +6775,8 @@ var ts; This_import_may_be_converted_to_a_type_only_import: diag(1372, ts.DiagnosticCategory.Suggestion, "This_import_may_be_converted_to_a_type_only_import_1372", "This import may be converted to a type-only import."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), - await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher: diag(1375, ts.DiagnosticCategory.Error, "await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnex_1375", "'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher."), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1376, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1376", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7706,7 +7722,7 @@ var ts; Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), @@ -7829,10 +7845,12 @@ var ts; Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"), Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), - can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"), An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), @@ -7847,6 +7865,7 @@ var ts; A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), @@ -26038,6 +26057,7 @@ var ts; error: 2 /* Error */ }), affectsEmit: true, + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types }, @@ -26295,12 +26315,15 @@ var ts; { name: "experimentalDecorators", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators }, { name: "emitDecoratorMetadata", type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, @@ -26314,6 +26337,7 @@ var ts; { name: "resolveJsonModule", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, @@ -26518,6 +26542,7 @@ var ts; name: "useDefineForClassFields", type: "boolean", affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set, }, @@ -30394,7 +30419,7 @@ var ts; case 104 /* ThisKeyword */: case 194 /* PropertyAccessExpression */: case 195 /* ElementAccessExpression */: - return isNarrowableReference(expr); + return containsNarrowableReference(expr); case 196 /* CallExpression */: return hasNarrowableArgument(expr); case 200 /* ParenthesizedExpression */: @@ -30411,20 +30436,22 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isOptionalChain(expr); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression); + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { var argument = _a[_i]; - if (isNarrowableReference(argument)) { + if (containsNarrowableReference(argument)) { return true; } } } if (expr.expression.kind === 194 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { + containsNarrowableReference(expr.expression.expression)) { return true; } return false; @@ -30438,7 +30465,7 @@ var ts; function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: - return isNarrowableReference(expr.left); + return containsNarrowableReference(expr.left); case 34 /* EqualsEqualsToken */: case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: @@ -30466,7 +30493,7 @@ var ts; return isNarrowableOperand(expr.right); } } - return isNarrowableReference(expr); + return containsNarrowableReference(expr); } function createBranchLabel() { return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); @@ -33878,6 +33905,7 @@ var ts; var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; + var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -34126,9 +34154,12 @@ var ts; isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule, + getSuggestionForNonexistentExport: getSuggestionForNonexistentExport, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -35720,9 +35751,11 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : @@ -45363,8 +45396,9 @@ var ts; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -47690,6 +47724,9 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -47884,6 +47921,12 @@ var ts; // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); + // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This + // effectively means we measure variance only from type parameter occurrences that aren't nested in + // recursive instantiations of the generic type. + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48669,8 +48712,7 @@ var ts; // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function - // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function - // has been invoked recursively for the given generic type. + // returns the emptyArray singleton when invoked recursively for the given generic type. function getVariancesWorker(typeParameters, cache, createMarkerType) { if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; @@ -48717,9 +48759,9 @@ var ts; return variances; } function getVariances(type) { - // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + // Arrays and tuples are known to be covariant, no need to spend time computing this. if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) { - return ts.emptyArray; + return arrayVariances; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } @@ -52425,24 +52467,7 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined - // they may have meant to specify the type as (() => T1 | ...) | undefined - // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of - // the union is `undefined` - if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { - var funcTypeNode = type.symbol.declarations[0]; - var returnType = getReturnTypeFromAnnotation(funcTypeNode); - if (returnType && returnType.flags & 1048576 /* Union */) { - var unionTypes_3 = funcTypeNode.type.types; - if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 146 /* UndefinedKeyword */) { - var parenedFuncType = ts.getMutableClone(funcTypeNode); - // Highlight to the end of the second to last constituent of the union - parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; - ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); - } - } - } + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } @@ -58057,12 +58082,17 @@ var ts; if (!(node.flags & 32768 /* AwaitContext */)) { if (isTopLevelAwait(node)) { var sourceFile = ts.getSourceFileOfNode(node); - if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || - languageVersion < 4 /* ES2017 */ || - !ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher); + if (!hasParseDiagnostics(sourceFile)) { + var span = void 0; + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } @@ -58072,7 +58102,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); @@ -96836,12 +96866,12 @@ var ts; if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { + // If root file names don't match + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { return false; } var seenResolvedRefs; - // If project references dont match + // If project references don't match if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { return false; } @@ -108965,7 +108995,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -109208,7 +109238,7 @@ var ts; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */)) { + if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) { var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; @@ -110532,6 +110562,8 @@ var ts; if (!contextToken) return undefined; switch (contextToken.kind) { + case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } + return undefined; case 26 /* SemicolonToken */: // class c {getValue(): number; | } case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } @@ -110658,8 +110690,12 @@ var ts; case 103 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 78 /* CaseKeyword */: - case 84 /* DefaultKeyword */: - return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 84 /* DefaultKeyword */: { + if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) { + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + } + return undefined; + } case 77 /* BreakKeyword */: case 82 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); @@ -112007,9 +112043,7 @@ var ts; return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false }); } var kind = entry.kind, node = entry.node; - return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 84 /* DefaultKeyword */ - || !!ts.getDeclarationFromName(node) - || ts.isLiteralComputedPropertyDeclarationName(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); + return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); } FindAllReferences.toReferenceEntry = toReferenceEntry; function entryToDocumentSpan(entry) { @@ -112117,6 +112151,12 @@ var ts; var decl = ts.getDeclarationFromName(node); return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node); } + function isDefinitionForReference(node) { + return node.kind === 84 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node) + || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent)); + } /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -122412,27 +122452,62 @@ var ts; this.insertNodeAtStartWorker(sourceFile, obj, newElement); }; ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { - var clsStart = cls.getStart(sourceFile); - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) - + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + var _a; + var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation)); }; - ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { - var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; - if (getMembersOrProperties(cls).length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { - // For `class C {\n}`, don't add the trailing "\n" - var _a = getClassOrObjectBraceEnds(cls, sourceFile), open = _a[0], close = _a[1]; - var shouldSuffix = open && close && ts.positionsAreOnSameLine(open, close, sourceFile); - return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + /** + * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on + * new lines and must share the same indentation. + */ + ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) { + var indentation; + var lastRange = cls; + for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) { + var member = _a[_i]; + if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) { + // each indented member must be on a new line + return undefined; } - else { - return { prefix: "", suffix: comma + this.newLineCharacter }; + var memberStart = member.getStart(sourceFile); + var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options); + if (indentation === undefined) { + indentation = memberIndentation; } + else if (memberIndentation !== indentation) { + // indentation of multiple members is not consistent + return undefined; + } + lastRange = member; } - else { - return { prefix: this.newLineCharacter, suffix: comma }; - } + return indentation; + }; + ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) { + var _a; + var clsStart = cls.getStart(sourceFile); + return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4); + }; + ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) { + // Rules: + // - Always insert leading newline. + // - For object literals: + // - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file + // (because trailing commas are generally illegal in a JSON file). + // - Add a leading comma if the source file is not a JSON file, there are existing insertions, + // and the node is empty (because we didn't add a trailing comma per the previous rule). + // - Only insert a trailing newline if body is single-line and there are no other insertions for the node. + // NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`. + var members = getMembersOrProperties(cls); + var isEmpty = members.length === 0; + var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile }); + var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty); + var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion; + return { + indentation: indentation, + prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, + suffix: insertTrailingComma ? "," : "" + }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); @@ -122634,9 +122709,16 @@ var ts; this.classesWithNodesInsertedAtStart.forEach(function (_a) { var node = _a.node, sourceFile = _a.sourceFile; var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; - // For `class C { }` remove the whitespace inside the braces. - if (openBraceEnd && closeBraceEnd && ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + if (openBraceEnd !== undefined && closeBraceEnd !== undefined) { + var isEmpty = getMembersOrProperties(node).length === 0; + var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile); + if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) { + // For `class C { }` remove the whitespace inside the braces. + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + if (isSingleLine) { + _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter); + } } }); }; @@ -123212,10 +123294,10 @@ var ts; ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) : ts.getLocaleSpecificMessage(diag); } - function createCodeFixActionNoFixId(fixName, changes, description) { + function createCodeFixActionWithoutFixAll(fixName, changes, description) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } - codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } @@ -123241,8 +123323,26 @@ var ts; return ts.arrayFrom(errorCodeToFixes.keys()); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function removeFixIdIfFixAllUnavailable(registration, diagnostics) { + var errorCodes = registration.errorCodes; + var maybeFixableDiagnostics = 0; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diag = diagnostics_1[_i]; + if (ts.contains(errorCodes, diag.code)) + maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) + break; + } + var fixAllUnavailable = maybeFixableDiagnostics < 2; + return function (_a) { + var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]); + return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription }); + }; + } function getFixes(context) { - return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + var diagnostics = getDiagnostics(context); + var registrations = errorCodeToFixes.get(String(context.errorCode)); + return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); }); } codefix.getFixes = getFixes; function getAllFixes(context) { @@ -123264,16 +123364,19 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function eachDiagnostic(_a, errorCodes, cb) { - var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { - var diag = _b[_i]; + function eachDiagnostic(context, errorCodes, cb) { + for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) { + var diag = _a[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); } } } codefix.eachDiagnostic = eachDiagnostic; + function getDiagnostics(_a) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + return program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -123330,6 +123433,28 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var exportDeclaration = ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createNamedExports([]), + /*moduleSpecifier*/ undefined, + /*isTypeOnly*/ false); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); + }); + return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)]; + }, + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -123400,7 +123525,9 @@ var ts; makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations); } }); - return codefix.createCodeFixActionNoFixId("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 + // No fix-all because it will already be included once with the use site fix, + // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes. + return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : ts.Diagnostics.Add_await_to_initializers); } @@ -123619,7 +123746,7 @@ var ts; if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); var parent = token.parent; - if (ts.isBinaryExpression(parent) && ts.isExpressionStatement(parent.parent)) { + if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) { return applyChange(changeTracker, token, sourceFile, fixedNodes); } if (ts.isArrayLiteralExpression(parent)) { @@ -123681,7 +123808,9 @@ var ts; if (expression.operatorToken.kind === 27 /* CommaToken */) { return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); }); } - return ts.isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); + return expression.operatorToken.kind === 62 /* EqualsToken */ + && ts.isIdentifier(expression.left) + && !checker.getSymbolAtLocation(expression.left); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -125672,7 +125801,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -126271,7 +126400,8 @@ var ts; (function (ts) { var codefix; (function (codefix) { - codefix.importFixId = "fixMissingImport"; + codefix.importFixName = "import"; + var importFixId = "fixMissingImport"; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, @@ -126292,7 +126422,7 @@ var ts; var quotePreference = ts.getQuotePreference(sourceFile, preferences); return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); }, - fixIds: [codefix.importFixId], + fixIds: [importFixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. @@ -126724,7 +126854,7 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); }); - return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports); } function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { switch (fix.kind) { @@ -127022,17 +127152,17 @@ var ts; var info = getInfo(sourceFile, context.span.start, context); if (!info) return undefined; - var node = info.node, suggestion = info.suggestion; + var node = info.node, suggestedSymbol = info.suggestedSymbol; var target = context.host.getCompilationSettings().target; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); - return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start, context); var target = context.host.getCompilationSettings().target; if (info) - doChange(changes, context.sourceFile, info.node, info.suggestion, target); + doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }); }, }); function getInfo(sourceFile, pos, context) { @@ -127041,34 +127171,42 @@ var ts; // ^^^^^^^ var node = ts.getTokenAtPosition(sourceFile, pos); var checker = context.program.getTypeChecker(); - var suggestion; + var suggestedSymbol; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(node.parent.expression); if (node.parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); } - suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + var name = node; + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (import)"); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); } } else { var meaning = ts.getMeaningFromLocation(node); var name = ts.getTextOfNode(node); ts.Debug.assert(name !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol }; } - function doChange(changes, sourceFile, node, suggestion, target) { + function doChange(changes, sourceFile, node, suggestedSymbol, target) { + var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { - changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + var valDecl = suggestedSymbol.valueDeclaration; + if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + else { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } } else { changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); @@ -127332,7 +127470,7 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { // Private methods are not implemented yet. @@ -127617,7 +127755,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); }); - return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; + return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) { @@ -127651,7 +127789,7 @@ var ts; return doChange(changeTracker, configFile); }); return [ - codefix.createCodeFixActionNoFixId(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) + codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) ]; }, fixIds: [fixID], @@ -127672,6 +127810,49 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + getCodeActions: function (context) { + var compilerOptions = context.program.getCompilerOptions(); + var configFile = compilerOptions.configFile; + if (configFile === undefined) { + return undefined; + } + var codeFixes = []; + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext; + if (moduleOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext")); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"])); + } + var target = ts.getEmitScriptTarget(compilerOptions); + var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */; + if (targetOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + var configObject = ts.getTsConfigObjectLiteralExpression(configFile); + if (!configObject) + return; + var options = [["target", ts.createStringLiteral("es2017")]]; + if (moduleKind === ts.ModuleKind.CommonJS) { + // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015. + options.push(["module", ts.createStringLiteral("commonjs")]); + } + codefix.setJsonCompilerOptionValues(tracker, configFile, options); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"])); + } + return codeFixes.length ? codeFixes : undefined; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -127824,7 +128005,7 @@ var ts; }); if (deletion.length) { var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)])); } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); @@ -128185,7 +128366,7 @@ var ts; (function (codefix) { var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ - ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, ]; codefix.registerCodeFix({ @@ -128277,7 +128458,7 @@ var ts; } var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), @@ -128544,29 +128725,37 @@ var ts; } return undefined; } - function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + function setJsonCompilerOptionValues(changeTracker, configFile, options) { var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ - createJsonPropertyAssignment(optionName, optionValue), - ]))); + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) { + var optionName = _a[0], optionValue = _a[1]; + return createJsonPropertyAssignment(optionName, optionValue); + }), /*multiLine*/ true))); return; } var compilerOptions = compilerOptionsProperty.initializer; if (!ts.isObjectLiteralExpression(compilerOptions)) { return; } - var optionProperty = findJsonProperty(compilerOptions, optionName); - if (optionProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); - } - else { - changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var _a = options_1[_i], optionName = _a[0], optionValue = _a[1]; + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } } } + codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues; + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]); + } codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; function createJsonPropertyAssignment(name, initializer) { return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); @@ -128601,7 +128790,7 @@ var ts; } function createAction(context, sourceFile, node, replacement) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -128659,7 +128848,7 @@ var ts; if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { var sourceFile_1 = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); }); - fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); } return fixes; } @@ -137184,7 +137373,8 @@ var ts; server.TextStorage = TextStorage; /*@internal*/ function isDynamicFileName(fileName) { - return fileName[0] === "^"; + return fileName[0] === "^" || + (ts.stringContains(fileName, ":^") && !ts.stringContains(fileName, ts.directorySeparator)); } server.isDynamicFileName = isDynamicFileName; var ScriptInfo = /** @class */ (function () { @@ -140277,7 +140467,7 @@ var ts; // Closing file should trigger re-reading the file content from disk. This is // because the user may chose to discard the buffer content before saving // to the disk, and the server's version of the file can be out of sync. - var fileExists = this.host.fileExists(info.fileName); + var fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName); info.close(fileExists); this.stopWatchingConfigFilesForClosedScriptInfo(info); var canonicalFileName = this.toCanonicalFileName(info.fileName); @@ -143277,7 +143467,11 @@ var ts; command: cmdName, request_seq: reqSeq, success: success, - updateGraphDurationMs: this.updateGraphDurationMs, + performanceData: !this.updateGraphDurationMs + ? undefined + : { + updateGraphDurationMs: this.updateGraphDurationMs, + }, }; if (success) { var metadata = void 0; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index d85e5ebdb0e..31d6a576497 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -63,6 +63,17 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || @@ -76,17 +87,6 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; /* @internal */ var ts; (function (ts) { @@ -1425,6 +1425,11 @@ var ts; return result; } ts.clone = clone; + /** + * Creates a new object by adding the own properties of `second`, then the own properties of `first`. + * + * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen. + */ function extend(first, second) { var result = {}; for (var id in second) { @@ -5745,10 +5750,13 @@ var ts; } } function readFileWorker(fileName, _encoding) { - if (!fileExists(fileName)) { + var buffer; + try { + buffer = _fs.readFileSync(fileName); + } + catch (e) { return undefined; } - var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, @@ -5798,23 +5806,30 @@ var ts; function getAccessibleFileSystemEntries(path) { ts.perfLogger.logEvent("ReadDir: " + (path || ".")); try { - var entries = _fs.readdirSync(path || ".").sort(); + var entries = _fs.readdirSync(path || ".", { withFileTypes: true }); var files = []; var directories = []; for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { - var entry = entries_2[_i]; + var dirent = entries_2[_i]; + // withFileTypes is not supported before Node 10.10. + var entry = typeof dirent === "string" ? dirent : dirent.name; // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); var stat = void 0; - try { - stat = _fs.statSync(name); + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + var name = ts.combinePaths(path, entry); + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } } - catch (e) { - continue; + else { + stat = dirent; } if (stat.isFile()) { files.push(entry); @@ -5823,6 +5838,8 @@ var ts; directories.push(entry); } } + files.sort(); + directories.sort(); return { files: files, directories: directories }; } catch (e) { @@ -5852,8 +5869,7 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - ts.perfLogger.logEvent("ReadDir: " + path); - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + return getAccessibleFileSystemEntries(path).directories.slice(); } function realpath(path) { try { @@ -6847,7 +6863,7 @@ var ts; Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), - await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), @@ -6895,14 +6911,13 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), Type_only_0_must_reference_a_type_but_1_is_a_value: diag(1361, ts.DiagnosticCategory.Error, "Type_only_0_must_reference_a_type_but_1_is_a_value_1361", "Type-only {0} must reference a type, but '{1}' is a value."), Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported: diag(1362, ts.DiagnosticCategory.Error, "Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported_1362", "Enum '{0}' cannot be used as a value because only its type has been imported."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"), Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), - Split_all_invalid_type_only_imports: diag(1377, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1377", "Split all invalid type-only imports"), + Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."), @@ -6910,7 +6925,8 @@ var ts; This_import_may_be_converted_to_a_type_only_import: diag(1372, ts.DiagnosticCategory.Suggestion, "This_import_may_be_converted_to_a_type_only_import_1372", "This import may be converted to a type-only import."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), - await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher: diag(1375, ts.DiagnosticCategory.Error, "await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnex_1375", "'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher."), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1376, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1376", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7856,7 +7872,7 @@ var ts; Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), @@ -7979,10 +7995,12 @@ var ts; Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"), Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), - can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"), An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), @@ -7997,6 +8015,7 @@ var ts; A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), @@ -26188,6 +26207,7 @@ var ts; error: 2 /* Error */ }), affectsEmit: true, + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types }, @@ -26445,12 +26465,15 @@ var ts; { name: "experimentalDecorators", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators }, { name: "emitDecoratorMetadata", type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, @@ -26464,6 +26487,7 @@ var ts; { name: "resolveJsonModule", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, @@ -26668,6 +26692,7 @@ var ts; name: "useDefineForClassFields", type: "boolean", affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set, }, @@ -30544,7 +30569,7 @@ var ts; case 104 /* ThisKeyword */: case 194 /* PropertyAccessExpression */: case 195 /* ElementAccessExpression */: - return isNarrowableReference(expr); + return containsNarrowableReference(expr); case 196 /* CallExpression */: return hasNarrowableArgument(expr); case 200 /* ParenthesizedExpression */: @@ -30561,20 +30586,22 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isOptionalChain(expr); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression); + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { var argument = _a[_i]; - if (isNarrowableReference(argument)) { + if (containsNarrowableReference(argument)) { return true; } } } if (expr.expression.kind === 194 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { + containsNarrowableReference(expr.expression.expression)) { return true; } return false; @@ -30588,7 +30615,7 @@ var ts; function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: - return isNarrowableReference(expr.left); + return containsNarrowableReference(expr.left); case 34 /* EqualsEqualsToken */: case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: @@ -30616,7 +30643,7 @@ var ts; return isNarrowableOperand(expr.right); } } - return isNarrowableReference(expr); + return containsNarrowableReference(expr); } function createBranchLabel() { return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); @@ -34028,6 +34055,7 @@ var ts; var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; + var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -34276,9 +34304,12 @@ var ts; isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule, + getSuggestionForNonexistentExport: getSuggestionForNonexistentExport, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -35870,9 +35901,11 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : @@ -45513,8 +45546,9 @@ var ts; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -47840,6 +47874,9 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48034,6 +48071,12 @@ var ts; // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); + // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This + // effectively means we measure variance only from type parameter occurrences that aren't nested in + // recursive instantiations of the generic type. + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48819,8 +48862,7 @@ var ts; // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function - // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function - // has been invoked recursively for the given generic type. + // returns the emptyArray singleton when invoked recursively for the given generic type. function getVariancesWorker(typeParameters, cache, createMarkerType) { if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; @@ -48867,9 +48909,9 @@ var ts; return variances; } function getVariances(type) { - // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + // Arrays and tuples are known to be covariant, no need to spend time computing this. if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) { - return ts.emptyArray; + return arrayVariances; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } @@ -52575,24 +52617,7 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined - // they may have meant to specify the type as (() => T1 | ...) | undefined - // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of - // the union is `undefined` - if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { - var funcTypeNode = type.symbol.declarations[0]; - var returnType = getReturnTypeFromAnnotation(funcTypeNode); - if (returnType && returnType.flags & 1048576 /* Union */) { - var unionTypes_3 = funcTypeNode.type.types; - if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 146 /* UndefinedKeyword */) { - var parenedFuncType = ts.getMutableClone(funcTypeNode); - // Highlight to the end of the second to last constituent of the union - parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; - ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); - } - } - } + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } @@ -58207,12 +58232,17 @@ var ts; if (!(node.flags & 32768 /* AwaitContext */)) { if (isTopLevelAwait(node)) { var sourceFile = ts.getSourceFileOfNode(node); - if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || - languageVersion < 4 /* ES2017 */ || - !ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher); + if (!hasParseDiagnostics(sourceFile)) { + var span = void 0; + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } @@ -58222,7 +58252,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); @@ -96986,12 +97016,12 @@ var ts; if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { + // If root file names don't match + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { return false; } var seenResolvedRefs; - // If project references dont match + // If project references don't match if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { return false; } @@ -109488,7 +109518,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -109731,7 +109761,7 @@ var ts; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */)) { + if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) { var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; @@ -111055,6 +111085,8 @@ var ts; if (!contextToken) return undefined; switch (contextToken.kind) { + case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } + return undefined; case 26 /* SemicolonToken */: // class c {getValue(): number; | } case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } @@ -111181,8 +111213,12 @@ var ts; case 103 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 78 /* CaseKeyword */: - case 84 /* DefaultKeyword */: - return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 84 /* DefaultKeyword */: { + if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) { + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + } + return undefined; + } case 77 /* BreakKeyword */: case 82 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); @@ -112530,9 +112566,7 @@ var ts; return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false }); } var kind = entry.kind, node = entry.node; - return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 84 /* DefaultKeyword */ - || !!ts.getDeclarationFromName(node) - || ts.isLiteralComputedPropertyDeclarationName(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); + return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); } FindAllReferences.toReferenceEntry = toReferenceEntry; function entryToDocumentSpan(entry) { @@ -112640,6 +112674,12 @@ var ts; var decl = ts.getDeclarationFromName(node); return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node); } + function isDefinitionForReference(node) { + return node.kind === 84 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node) + || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent)); + } /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -122935,27 +122975,62 @@ var ts; this.insertNodeAtStartWorker(sourceFile, obj, newElement); }; ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { - var clsStart = cls.getStart(sourceFile); - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) - + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + var _a; + var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation)); }; - ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { - var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; - if (getMembersOrProperties(cls).length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { - // For `class C {\n}`, don't add the trailing "\n" - var _a = getClassOrObjectBraceEnds(cls, sourceFile), open = _a[0], close = _a[1]; - var shouldSuffix = open && close && ts.positionsAreOnSameLine(open, close, sourceFile); - return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + /** + * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on + * new lines and must share the same indentation. + */ + ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) { + var indentation; + var lastRange = cls; + for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) { + var member = _a[_i]; + if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) { + // each indented member must be on a new line + return undefined; } - else { - return { prefix: "", suffix: comma + this.newLineCharacter }; + var memberStart = member.getStart(sourceFile); + var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options); + if (indentation === undefined) { + indentation = memberIndentation; } + else if (memberIndentation !== indentation) { + // indentation of multiple members is not consistent + return undefined; + } + lastRange = member; } - else { - return { prefix: this.newLineCharacter, suffix: comma }; - } + return indentation; + }; + ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) { + var _a; + var clsStart = cls.getStart(sourceFile); + return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4); + }; + ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) { + // Rules: + // - Always insert leading newline. + // - For object literals: + // - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file + // (because trailing commas are generally illegal in a JSON file). + // - Add a leading comma if the source file is not a JSON file, there are existing insertions, + // and the node is empty (because we didn't add a trailing comma per the previous rule). + // - Only insert a trailing newline if body is single-line and there are no other insertions for the node. + // NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`. + var members = getMembersOrProperties(cls); + var isEmpty = members.length === 0; + var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile }); + var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty); + var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion; + return { + indentation: indentation, + prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, + suffix: insertTrailingComma ? "," : "" + }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); @@ -123157,9 +123232,16 @@ var ts; this.classesWithNodesInsertedAtStart.forEach(function (_a) { var node = _a.node, sourceFile = _a.sourceFile; var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; - // For `class C { }` remove the whitespace inside the braces. - if (openBraceEnd && closeBraceEnd && ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + if (openBraceEnd !== undefined && closeBraceEnd !== undefined) { + var isEmpty = getMembersOrProperties(node).length === 0; + var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile); + if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) { + // For `class C { }` remove the whitespace inside the braces. + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + if (isSingleLine) { + _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter); + } } }); }; @@ -123735,10 +123817,10 @@ var ts; ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) : ts.getLocaleSpecificMessage(diag); } - function createCodeFixActionNoFixId(fixName, changes, description) { + function createCodeFixActionWithoutFixAll(fixName, changes, description) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } - codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } @@ -123764,8 +123846,26 @@ var ts; return ts.arrayFrom(errorCodeToFixes.keys()); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function removeFixIdIfFixAllUnavailable(registration, diagnostics) { + var errorCodes = registration.errorCodes; + var maybeFixableDiagnostics = 0; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diag = diagnostics_1[_i]; + if (ts.contains(errorCodes, diag.code)) + maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) + break; + } + var fixAllUnavailable = maybeFixableDiagnostics < 2; + return function (_a) { + var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]); + return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription }); + }; + } function getFixes(context) { - return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + var diagnostics = getDiagnostics(context); + var registrations = errorCodeToFixes.get(String(context.errorCode)); + return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); }); } codefix.getFixes = getFixes; function getAllFixes(context) { @@ -123787,16 +123887,19 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function eachDiagnostic(_a, errorCodes, cb) { - var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { - var diag = _b[_i]; + function eachDiagnostic(context, errorCodes, cb) { + for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) { + var diag = _a[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); } } } codefix.eachDiagnostic = eachDiagnostic; + function getDiagnostics(_a) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + return program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -123853,6 +123956,28 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var exportDeclaration = ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createNamedExports([]), + /*moduleSpecifier*/ undefined, + /*isTypeOnly*/ false); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); + }); + return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)]; + }, + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -123923,7 +124048,9 @@ var ts; makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations); } }); - return codefix.createCodeFixActionNoFixId("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 + // No fix-all because it will already be included once with the use site fix, + // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes. + return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : ts.Diagnostics.Add_await_to_initializers); } @@ -124142,7 +124269,7 @@ var ts; if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); var parent = token.parent; - if (ts.isBinaryExpression(parent) && ts.isExpressionStatement(parent.parent)) { + if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) { return applyChange(changeTracker, token, sourceFile, fixedNodes); } if (ts.isArrayLiteralExpression(parent)) { @@ -124204,7 +124331,9 @@ var ts; if (expression.operatorToken.kind === 27 /* CommaToken */) { return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); }); } - return ts.isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); + return expression.operatorToken.kind === 62 /* EqualsToken */ + && ts.isIdentifier(expression.left) + && !checker.getSymbolAtLocation(expression.left); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -126195,7 +126324,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -126794,7 +126923,8 @@ var ts; (function (ts) { var codefix; (function (codefix) { - codefix.importFixId = "fixMissingImport"; + codefix.importFixName = "import"; + var importFixId = "fixMissingImport"; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, @@ -126815,7 +126945,7 @@ var ts; var quotePreference = ts.getQuotePreference(sourceFile, preferences); return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); }, - fixIds: [codefix.importFixId], + fixIds: [importFixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. @@ -127247,7 +127377,7 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); }); - return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports); } function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { switch (fix.kind) { @@ -127545,17 +127675,17 @@ var ts; var info = getInfo(sourceFile, context.span.start, context); if (!info) return undefined; - var node = info.node, suggestion = info.suggestion; + var node = info.node, suggestedSymbol = info.suggestedSymbol; var target = context.host.getCompilationSettings().target; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); - return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start, context); var target = context.host.getCompilationSettings().target; if (info) - doChange(changes, context.sourceFile, info.node, info.suggestion, target); + doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }); }, }); function getInfo(sourceFile, pos, context) { @@ -127564,34 +127694,42 @@ var ts; // ^^^^^^^ var node = ts.getTokenAtPosition(sourceFile, pos); var checker = context.program.getTypeChecker(); - var suggestion; + var suggestedSymbol; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(node.parent.expression); if (node.parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); } - suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + var name = node; + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (import)"); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); } } else { var meaning = ts.getMeaningFromLocation(node); var name = ts.getTextOfNode(node); ts.Debug.assert(name !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol }; } - function doChange(changes, sourceFile, node, suggestion, target) { + function doChange(changes, sourceFile, node, suggestedSymbol, target) { + var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { - changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + var valDecl = suggestedSymbol.valueDeclaration; + if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + else { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } } else { changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); @@ -127855,7 +127993,7 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { // Private methods are not implemented yet. @@ -128140,7 +128278,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); }); - return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; + return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) { @@ -128174,7 +128312,7 @@ var ts; return doChange(changeTracker, configFile); }); return [ - codefix.createCodeFixActionNoFixId(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) + codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) ]; }, fixIds: [fixID], @@ -128195,6 +128333,49 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + getCodeActions: function (context) { + var compilerOptions = context.program.getCompilerOptions(); + var configFile = compilerOptions.configFile; + if (configFile === undefined) { + return undefined; + } + var codeFixes = []; + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext; + if (moduleOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext")); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"])); + } + var target = ts.getEmitScriptTarget(compilerOptions); + var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */; + if (targetOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + var configObject = ts.getTsConfigObjectLiteralExpression(configFile); + if (!configObject) + return; + var options = [["target", ts.createStringLiteral("es2017")]]; + if (moduleKind === ts.ModuleKind.CommonJS) { + // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015. + options.push(["module", ts.createStringLiteral("commonjs")]); + } + codefix.setJsonCompilerOptionValues(tracker, configFile, options); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"])); + } + return codeFixes.length ? codeFixes : undefined; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -128347,7 +128528,7 @@ var ts; }); if (deletion.length) { var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)])); } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); @@ -128708,7 +128889,7 @@ var ts; (function (codefix) { var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ - ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, ]; codefix.registerCodeFix({ @@ -128800,7 +128981,7 @@ var ts; } var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), @@ -129067,29 +129248,37 @@ var ts; } return undefined; } - function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + function setJsonCompilerOptionValues(changeTracker, configFile, options) { var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ - createJsonPropertyAssignment(optionName, optionValue), - ]))); + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) { + var optionName = _a[0], optionValue = _a[1]; + return createJsonPropertyAssignment(optionName, optionValue); + }), /*multiLine*/ true))); return; } var compilerOptions = compilerOptionsProperty.initializer; if (!ts.isObjectLiteralExpression(compilerOptions)) { return; } - var optionProperty = findJsonProperty(compilerOptions, optionName); - if (optionProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); - } - else { - changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var _a = options_1[_i], optionName = _a[0], optionValue = _a[1]; + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } } } + codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues; + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]); + } codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; function createJsonPropertyAssignment(name, initializer) { return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); @@ -129124,7 +129313,7 @@ var ts; } function createAction(context, sourceFile, node, replacement) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -129182,7 +129371,7 @@ var ts; if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { var sourceFile_1 = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); }); - fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); } return fixes; } @@ -137334,7 +137523,8 @@ var ts; server.TextStorage = TextStorage; /*@internal*/ function isDynamicFileName(fileName) { - return fileName[0] === "^"; + return fileName[0] === "^" || + (ts.stringContains(fileName, ":^") && !ts.stringContains(fileName, ts.directorySeparator)); } server.isDynamicFileName = isDynamicFileName; var ScriptInfo = /** @class */ (function () { @@ -140427,7 +140617,7 @@ var ts; // Closing file should trigger re-reading the file content from disk. This is // because the user may chose to discard the buffer content before saving // to the disk, and the server's version of the file can be out of sync. - var fileExists = this.host.fileExists(info.fileName); + var fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName); info.close(fileExists); this.stopWatchingConfigFilesForClosedScriptInfo(info); var canonicalFileName = this.toCanonicalFileName(info.fileName); @@ -143427,7 +143617,11 @@ var ts; command: cmdName, request_seq: reqSeq, success: success, - updateGraphDurationMs: this.updateGraphDurationMs, + performanceData: !this.updateGraphDurationMs + ? undefined + : { + updateGraphDurationMs: this.updateGraphDurationMs, + }, }; if (success) { var metadata = void 0; diff --git a/lib/typescript.js b/lib/typescript.js index 382f819640f..147a6c200bf 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -63,6 +63,17 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || @@ -1414,6 +1425,11 @@ var ts; return result; } ts.clone = clone; + /** + * Creates a new object by adding the own properties of `second`, then the own properties of `first`. + * + * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen. + */ function extend(first, second) { var result = {}; for (var id in second) { @@ -5734,10 +5750,13 @@ var ts; } } function readFileWorker(fileName, _encoding) { - if (!fileExists(fileName)) { + var buffer; + try { + buffer = _fs.readFileSync(fileName); + } + catch (e) { return undefined; } - var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, @@ -5787,23 +5806,30 @@ var ts; function getAccessibleFileSystemEntries(path) { ts.perfLogger.logEvent("ReadDir: " + (path || ".")); try { - var entries = _fs.readdirSync(path || ".").sort(); + var entries = _fs.readdirSync(path || ".", { withFileTypes: true }); var files = []; var directories = []; for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { - var entry = entries_2[_i]; + var dirent = entries_2[_i]; + // withFileTypes is not supported before Node 10.10. + var entry = typeof dirent === "string" ? dirent : dirent.name; // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); var stat = void 0; - try { - stat = _fs.statSync(name); + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + var name = ts.combinePaths(path, entry); + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } } - catch (e) { - continue; + else { + stat = dirent; } if (stat.isFile()) { files.push(entry); @@ -5812,6 +5838,8 @@ var ts; directories.push(entry); } } + files.sort(); + directories.sort(); return { files: files, directories: directories }; } catch (e) { @@ -5841,8 +5869,7 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - ts.perfLogger.logEvent("ReadDir: " + path); - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + return getAccessibleFileSystemEntries(path).directories.slice(); } function realpath(path) { try { @@ -6836,7 +6863,7 @@ var ts; Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), - await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), @@ -6884,14 +6911,13 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), Type_only_0_must_reference_a_type_but_1_is_a_value: diag(1361, ts.DiagnosticCategory.Error, "Type_only_0_must_reference_a_type_but_1_is_a_value_1361", "Type-only {0} must reference a type, but '{1}' is a value."), Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported: diag(1362, ts.DiagnosticCategory.Error, "Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported_1362", "Enum '{0}' cannot be used as a value because only its type has been imported."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"), Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), - Split_all_invalid_type_only_imports: diag(1377, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1377", "Split all invalid type-only imports"), + Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."), @@ -6899,7 +6925,8 @@ var ts; This_import_may_be_converted_to_a_type_only_import: diag(1372, ts.DiagnosticCategory.Suggestion, "This_import_may_be_converted_to_a_type_only_import_1372", "This import may be converted to a type-only import."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), - await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher: diag(1375, ts.DiagnosticCategory.Error, "await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnex_1375", "'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher."), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1376, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1376", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7845,7 +7872,7 @@ var ts; Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), @@ -7968,10 +7995,12 @@ var ts; Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"), Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), - can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"), An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), @@ -7986,6 +8015,7 @@ var ts; A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), @@ -26177,6 +26207,7 @@ var ts; error: 2 /* Error */ }), affectsEmit: true, + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types }, @@ -26434,12 +26465,15 @@ var ts; { name: "experimentalDecorators", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators }, { name: "emitDecoratorMetadata", type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, @@ -26453,6 +26487,7 @@ var ts; { name: "resolveJsonModule", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, @@ -26657,6 +26692,7 @@ var ts; name: "useDefineForClassFields", type: "boolean", affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set, }, @@ -30533,7 +30569,7 @@ var ts; case 104 /* ThisKeyword */: case 194 /* PropertyAccessExpression */: case 195 /* ElementAccessExpression */: - return isNarrowableReference(expr); + return containsNarrowableReference(expr); case 196 /* CallExpression */: return hasNarrowableArgument(expr); case 200 /* ParenthesizedExpression */: @@ -30550,20 +30586,22 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isOptionalChain(expr); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression); + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { var argument = _a[_i]; - if (isNarrowableReference(argument)) { + if (containsNarrowableReference(argument)) { return true; } } } if (expr.expression.kind === 194 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { + containsNarrowableReference(expr.expression.expression)) { return true; } return false; @@ -30577,7 +30615,7 @@ var ts; function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: - return isNarrowableReference(expr.left); + return containsNarrowableReference(expr.left); case 34 /* EqualsEqualsToken */: case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: @@ -30605,7 +30643,7 @@ var ts; return isNarrowableOperand(expr.right); } } - return isNarrowableReference(expr); + return containsNarrowableReference(expr); } function createBranchLabel() { return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); @@ -34017,6 +34055,7 @@ var ts; var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; + var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -34265,9 +34304,12 @@ var ts; isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule, + getSuggestionForNonexistentExport: getSuggestionForNonexistentExport, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -35859,9 +35901,11 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : @@ -45502,8 +45546,9 @@ var ts; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -47829,6 +47874,9 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48023,6 +48071,12 @@ var ts; // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); + // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This + // effectively means we measure variance only from type parameter occurrences that aren't nested in + // recursive instantiations of the generic type. + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48808,8 +48862,7 @@ var ts; // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function - // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function - // has been invoked recursively for the given generic type. + // returns the emptyArray singleton when invoked recursively for the given generic type. function getVariancesWorker(typeParameters, cache, createMarkerType) { if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; @@ -48856,9 +48909,9 @@ var ts; return variances; } function getVariances(type) { - // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + // Arrays and tuples are known to be covariant, no need to spend time computing this. if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) { - return ts.emptyArray; + return arrayVariances; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } @@ -52564,24 +52617,7 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined - // they may have meant to specify the type as (() => T1 | ...) | undefined - // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of - // the union is `undefined` - if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { - var funcTypeNode = type.symbol.declarations[0]; - var returnType = getReturnTypeFromAnnotation(funcTypeNode); - if (returnType && returnType.flags & 1048576 /* Union */) { - var unionTypes_3 = funcTypeNode.type.types; - if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 146 /* UndefinedKeyword */) { - var parenedFuncType = ts.getMutableClone(funcTypeNode); - // Highlight to the end of the second to last constituent of the union - parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; - ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); - } - } - } + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } @@ -58196,12 +58232,17 @@ var ts; if (!(node.flags & 32768 /* AwaitContext */)) { if (isTopLevelAwait(node)) { var sourceFile = ts.getSourceFileOfNode(node); - if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || - languageVersion < 4 /* ES2017 */ || - !ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher); + if (!hasParseDiagnostics(sourceFile)) { + var span = void 0; + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } @@ -58211,7 +58252,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); @@ -96975,12 +97016,12 @@ var ts; if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { + // If root file names don't match + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { return false; } var seenResolvedRefs; - // If project references dont match + // If project references don't match if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { return false; } @@ -109477,7 +109518,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -109720,7 +109761,7 @@ var ts; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */)) { + if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) { var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; @@ -111044,6 +111085,8 @@ var ts; if (!contextToken) return undefined; switch (contextToken.kind) { + case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } + return undefined; case 26 /* SemicolonToken */: // class c {getValue(): number; | } case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } @@ -111170,8 +111213,12 @@ var ts; case 103 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 78 /* CaseKeyword */: - case 84 /* DefaultKeyword */: - return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 84 /* DefaultKeyword */: { + if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) { + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + } + return undefined; + } case 77 /* BreakKeyword */: case 82 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); @@ -112519,9 +112566,7 @@ var ts; return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false }); } var kind = entry.kind, node = entry.node; - return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 84 /* DefaultKeyword */ - || !!ts.getDeclarationFromName(node) - || ts.isLiteralComputedPropertyDeclarationName(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); + return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); } FindAllReferences.toReferenceEntry = toReferenceEntry; function entryToDocumentSpan(entry) { @@ -112629,6 +112674,12 @@ var ts; var decl = ts.getDeclarationFromName(node); return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node); } + function isDefinitionForReference(node) { + return node.kind === 84 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node) + || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent)); + } /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -122924,27 +122975,62 @@ var ts; this.insertNodeAtStartWorker(sourceFile, obj, newElement); }; ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { - var clsStart = cls.getStart(sourceFile); - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) - + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + var _a; + var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation)); }; - ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { - var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; - if (getMembersOrProperties(cls).length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { - // For `class C {\n}`, don't add the trailing "\n" - var _a = getClassOrObjectBraceEnds(cls, sourceFile), open = _a[0], close = _a[1]; - var shouldSuffix = open && close && ts.positionsAreOnSameLine(open, close, sourceFile); - return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + /** + * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on + * new lines and must share the same indentation. + */ + ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) { + var indentation; + var lastRange = cls; + for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) { + var member = _a[_i]; + if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) { + // each indented member must be on a new line + return undefined; } - else { - return { prefix: "", suffix: comma + this.newLineCharacter }; + var memberStart = member.getStart(sourceFile); + var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options); + if (indentation === undefined) { + indentation = memberIndentation; } + else if (memberIndentation !== indentation) { + // indentation of multiple members is not consistent + return undefined; + } + lastRange = member; } - else { - return { prefix: this.newLineCharacter, suffix: comma }; - } + return indentation; + }; + ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) { + var _a; + var clsStart = cls.getStart(sourceFile); + return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4); + }; + ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) { + // Rules: + // - Always insert leading newline. + // - For object literals: + // - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file + // (because trailing commas are generally illegal in a JSON file). + // - Add a leading comma if the source file is not a JSON file, there are existing insertions, + // and the node is empty (because we didn't add a trailing comma per the previous rule). + // - Only insert a trailing newline if body is single-line and there are no other insertions for the node. + // NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`. + var members = getMembersOrProperties(cls); + var isEmpty = members.length === 0; + var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile }); + var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty); + var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion; + return { + indentation: indentation, + prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, + suffix: insertTrailingComma ? "," : "" + }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); @@ -123146,9 +123232,16 @@ var ts; this.classesWithNodesInsertedAtStart.forEach(function (_a) { var node = _a.node, sourceFile = _a.sourceFile; var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; - // For `class C { }` remove the whitespace inside the braces. - if (openBraceEnd && closeBraceEnd && ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + if (openBraceEnd !== undefined && closeBraceEnd !== undefined) { + var isEmpty = getMembersOrProperties(node).length === 0; + var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile); + if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) { + // For `class C { }` remove the whitespace inside the braces. + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + if (isSingleLine) { + _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter); + } } }); }; @@ -123724,10 +123817,10 @@ var ts; ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) : ts.getLocaleSpecificMessage(diag); } - function createCodeFixActionNoFixId(fixName, changes, description) { + function createCodeFixActionWithoutFixAll(fixName, changes, description) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } - codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } @@ -123753,8 +123846,26 @@ var ts; return ts.arrayFrom(errorCodeToFixes.keys()); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function removeFixIdIfFixAllUnavailable(registration, diagnostics) { + var errorCodes = registration.errorCodes; + var maybeFixableDiagnostics = 0; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diag = diagnostics_1[_i]; + if (ts.contains(errorCodes, diag.code)) + maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) + break; + } + var fixAllUnavailable = maybeFixableDiagnostics < 2; + return function (_a) { + var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]); + return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription }); + }; + } function getFixes(context) { - return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + var diagnostics = getDiagnostics(context); + var registrations = errorCodeToFixes.get(String(context.errorCode)); + return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); }); } codefix.getFixes = getFixes; function getAllFixes(context) { @@ -123776,16 +123887,19 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function eachDiagnostic(_a, errorCodes, cb) { - var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { - var diag = _b[_i]; + function eachDiagnostic(context, errorCodes, cb) { + for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) { + var diag = _a[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); } } } codefix.eachDiagnostic = eachDiagnostic; + function getDiagnostics(_a) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + return program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -123842,6 +123956,28 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var exportDeclaration = ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createNamedExports([]), + /*moduleSpecifier*/ undefined, + /*isTypeOnly*/ false); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); + }); + return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)]; + }, + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -123912,7 +124048,9 @@ var ts; makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations); } }); - return codefix.createCodeFixActionNoFixId("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 + // No fix-all because it will already be included once with the use site fix, + // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes. + return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : ts.Diagnostics.Add_await_to_initializers); } @@ -124131,7 +124269,7 @@ var ts; if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); var parent = token.parent; - if (ts.isBinaryExpression(parent) && ts.isExpressionStatement(parent.parent)) { + if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) { return applyChange(changeTracker, token, sourceFile, fixedNodes); } if (ts.isArrayLiteralExpression(parent)) { @@ -124193,7 +124331,9 @@ var ts; if (expression.operatorToken.kind === 27 /* CommaToken */) { return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); }); } - return ts.isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); + return expression.operatorToken.kind === 62 /* EqualsToken */ + && ts.isIdentifier(expression.left) + && !checker.getSymbolAtLocation(expression.left); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -126184,7 +126324,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -126783,7 +126923,8 @@ var ts; (function (ts) { var codefix; (function (codefix) { - codefix.importFixId = "fixMissingImport"; + codefix.importFixName = "import"; + var importFixId = "fixMissingImport"; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, @@ -126804,7 +126945,7 @@ var ts; var quotePreference = ts.getQuotePreference(sourceFile, preferences); return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); }, - fixIds: [codefix.importFixId], + fixIds: [importFixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. @@ -127236,7 +127377,7 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); }); - return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports); } function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { switch (fix.kind) { @@ -127534,17 +127675,17 @@ var ts; var info = getInfo(sourceFile, context.span.start, context); if (!info) return undefined; - var node = info.node, suggestion = info.suggestion; + var node = info.node, suggestedSymbol = info.suggestedSymbol; var target = context.host.getCompilationSettings().target; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); - return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start, context); var target = context.host.getCompilationSettings().target; if (info) - doChange(changes, context.sourceFile, info.node, info.suggestion, target); + doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }); }, }); function getInfo(sourceFile, pos, context) { @@ -127553,34 +127694,42 @@ var ts; // ^^^^^^^ var node = ts.getTokenAtPosition(sourceFile, pos); var checker = context.program.getTypeChecker(); - var suggestion; + var suggestedSymbol; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(node.parent.expression); if (node.parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); } - suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + var name = node; + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (import)"); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); } } else { var meaning = ts.getMeaningFromLocation(node); var name = ts.getTextOfNode(node); ts.Debug.assert(name !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol }; } - function doChange(changes, sourceFile, node, suggestion, target) { + function doChange(changes, sourceFile, node, suggestedSymbol, target) { + var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { - changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + var valDecl = suggestedSymbol.valueDeclaration; + if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + else { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } } else { changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); @@ -127844,7 +127993,7 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { // Private methods are not implemented yet. @@ -128129,7 +128278,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); }); - return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; + return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) { @@ -128163,7 +128312,7 @@ var ts; return doChange(changeTracker, configFile); }); return [ - codefix.createCodeFixActionNoFixId(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) + codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) ]; }, fixIds: [fixID], @@ -128184,6 +128333,49 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + getCodeActions: function (context) { + var compilerOptions = context.program.getCompilerOptions(); + var configFile = compilerOptions.configFile; + if (configFile === undefined) { + return undefined; + } + var codeFixes = []; + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext; + if (moduleOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext")); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"])); + } + var target = ts.getEmitScriptTarget(compilerOptions); + var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */; + if (targetOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + var configObject = ts.getTsConfigObjectLiteralExpression(configFile); + if (!configObject) + return; + var options = [["target", ts.createStringLiteral("es2017")]]; + if (moduleKind === ts.ModuleKind.CommonJS) { + // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015. + options.push(["module", ts.createStringLiteral("commonjs")]); + } + codefix.setJsonCompilerOptionValues(tracker, configFile, options); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"])); + } + return codeFixes.length ? codeFixes : undefined; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -128336,7 +128528,7 @@ var ts; }); if (deletion.length) { var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)])); } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); @@ -128697,7 +128889,7 @@ var ts; (function (codefix) { var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ - ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, ]; codefix.registerCodeFix({ @@ -128789,7 +128981,7 @@ var ts; } var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), @@ -129056,29 +129248,37 @@ var ts; } return undefined; } - function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + function setJsonCompilerOptionValues(changeTracker, configFile, options) { var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ - createJsonPropertyAssignment(optionName, optionValue), - ]))); + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) { + var optionName = _a[0], optionValue = _a[1]; + return createJsonPropertyAssignment(optionName, optionValue); + }), /*multiLine*/ true))); return; } var compilerOptions = compilerOptionsProperty.initializer; if (!ts.isObjectLiteralExpression(compilerOptions)) { return; } - var optionProperty = findJsonProperty(compilerOptions, optionName); - if (optionProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); - } - else { - changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var _a = options_1[_i], optionName = _a[0], optionValue = _a[1]; + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } } } + codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues; + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]); + } codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; function createJsonPropertyAssignment(name, initializer) { return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); @@ -129113,7 +129313,7 @@ var ts; } function createAction(context, sourceFile, node, replacement) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -129171,7 +129371,7 @@ var ts; if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { var sourceFile_1 = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); }); - fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); } return fixes; } diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index c271b332e67..d434587d9d5 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -63,6 +63,17 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || @@ -1414,6 +1425,11 @@ var ts; return result; } ts.clone = clone; + /** + * Creates a new object by adding the own properties of `second`, then the own properties of `first`. + * + * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen. + */ function extend(first, second) { var result = {}; for (var id in second) { @@ -5734,10 +5750,13 @@ var ts; } } function readFileWorker(fileName, _encoding) { - if (!fileExists(fileName)) { + var buffer; + try { + buffer = _fs.readFileSync(fileName); + } + catch (e) { return undefined; } - var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, @@ -5787,23 +5806,30 @@ var ts; function getAccessibleFileSystemEntries(path) { ts.perfLogger.logEvent("ReadDir: " + (path || ".")); try { - var entries = _fs.readdirSync(path || ".").sort(); + var entries = _fs.readdirSync(path || ".", { withFileTypes: true }); var files = []; var directories = []; for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { - var entry = entries_2[_i]; + var dirent = entries_2[_i]; + // withFileTypes is not supported before Node 10.10. + var entry = typeof dirent === "string" ? dirent : dirent.name; // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); var stat = void 0; - try { - stat = _fs.statSync(name); + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + var name = ts.combinePaths(path, entry); + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } } - catch (e) { - continue; + else { + stat = dirent; } if (stat.isFile()) { files.push(entry); @@ -5812,6 +5838,8 @@ var ts; directories.push(entry); } } + files.sort(); + directories.sort(); return { files: files, directories: directories }; } catch (e) { @@ -5841,8 +5869,7 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - ts.perfLogger.logEvent("ReadDir: " + path); - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + return getAccessibleFileSystemEntries(path).directories.slice(); } function realpath(path) { try { @@ -6836,7 +6863,7 @@ var ts; Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), - await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), @@ -6884,14 +6911,13 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), Type_only_0_must_reference_a_type_but_1_is_a_value: diag(1361, ts.DiagnosticCategory.Error, "Type_only_0_must_reference_a_type_but_1_is_a_value_1361", "Type-only {0} must reference a type, but '{1}' is a value."), Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported: diag(1362, ts.DiagnosticCategory.Error, "Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported_1362", "Enum '{0}' cannot be used as a value because only its type has been imported."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"), Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), - Split_all_invalid_type_only_imports: diag(1377, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1377", "Split all invalid type-only imports"), + Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."), @@ -6899,7 +6925,8 @@ var ts; This_import_may_be_converted_to_a_type_only_import: diag(1372, ts.DiagnosticCategory.Suggestion, "This_import_may_be_converted_to_a_type_only_import_1372", "This import may be converted to a type-only import."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), - await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher: diag(1375, ts.DiagnosticCategory.Error, "await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnex_1375", "'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher."), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1376, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1376", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7845,7 +7872,7 @@ var ts; Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), @@ -7968,10 +7995,12 @@ var ts; Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"), Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), - can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"), An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), @@ -7986,6 +8015,7 @@ var ts; A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), @@ -26177,6 +26207,7 @@ var ts; error: 2 /* Error */ }), affectsEmit: true, + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types }, @@ -26434,12 +26465,15 @@ var ts; { name: "experimentalDecorators", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators }, { name: "emitDecoratorMetadata", type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, @@ -26453,6 +26487,7 @@ var ts; { name: "resolveJsonModule", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, @@ -26657,6 +26692,7 @@ var ts; name: "useDefineForClassFields", type: "boolean", affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set, }, @@ -30533,7 +30569,7 @@ var ts; case 104 /* ThisKeyword */: case 194 /* PropertyAccessExpression */: case 195 /* ElementAccessExpression */: - return isNarrowableReference(expr); + return containsNarrowableReference(expr); case 196 /* CallExpression */: return hasNarrowableArgument(expr); case 200 /* ParenthesizedExpression */: @@ -30550,20 +30586,22 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isOptionalChain(expr); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression); + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { var argument = _a[_i]; - if (isNarrowableReference(argument)) { + if (containsNarrowableReference(argument)) { return true; } } } if (expr.expression.kind === 194 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { + containsNarrowableReference(expr.expression.expression)) { return true; } return false; @@ -30577,7 +30615,7 @@ var ts; function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: - return isNarrowableReference(expr.left); + return containsNarrowableReference(expr.left); case 34 /* EqualsEqualsToken */: case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: @@ -30605,7 +30643,7 @@ var ts; return isNarrowableOperand(expr.right); } } - return isNarrowableReference(expr); + return containsNarrowableReference(expr); } function createBranchLabel() { return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); @@ -34017,6 +34055,7 @@ var ts; var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; + var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -34265,9 +34304,12 @@ var ts; isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule, + getSuggestionForNonexistentExport: getSuggestionForNonexistentExport, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -35859,9 +35901,11 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : @@ -45502,8 +45546,9 @@ var ts; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -47829,6 +47874,9 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48023,6 +48071,12 @@ var ts; // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); + // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This + // effectively means we measure variance only from type parameter occurrences that aren't nested in + // recursive instantiations of the generic type. + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48808,8 +48862,7 @@ var ts; // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function - // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function - // has been invoked recursively for the given generic type. + // returns the emptyArray singleton when invoked recursively for the given generic type. function getVariancesWorker(typeParameters, cache, createMarkerType) { if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; @@ -48856,9 +48909,9 @@ var ts; return variances; } function getVariances(type) { - // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + // Arrays and tuples are known to be covariant, no need to spend time computing this. if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) { - return ts.emptyArray; + return arrayVariances; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } @@ -52564,24 +52617,7 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined - // they may have meant to specify the type as (() => T1 | ...) | undefined - // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of - // the union is `undefined` - if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { - var funcTypeNode = type.symbol.declarations[0]; - var returnType = getReturnTypeFromAnnotation(funcTypeNode); - if (returnType && returnType.flags & 1048576 /* Union */) { - var unionTypes_3 = funcTypeNode.type.types; - if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 146 /* UndefinedKeyword */) { - var parenedFuncType = ts.getMutableClone(funcTypeNode); - // Highlight to the end of the second to last constituent of the union - parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; - ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); - } - } - } + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } @@ -58196,12 +58232,17 @@ var ts; if (!(node.flags & 32768 /* AwaitContext */)) { if (isTopLevelAwait(node)) { var sourceFile = ts.getSourceFileOfNode(node); - if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || - languageVersion < 4 /* ES2017 */ || - !ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher); + if (!hasParseDiagnostics(sourceFile)) { + var span = void 0; + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } @@ -58211,7 +58252,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); @@ -96975,12 +97016,12 @@ var ts; if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { + // If root file names don't match + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { return false; } var seenResolvedRefs; - // If project references dont match + // If project references don't match if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { return false; } @@ -109477,7 +109518,7 @@ var ts; var contextToken = previousToken; // Check if the caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS| // Skip this partial identifier and adjust the contextToken to the token that precedes it. - if (contextToken && position <= contextToken.end && (ts.isIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { + if (contextToken && position <= contextToken.end && (ts.isIdentifierOrPrivateIdentifier(contextToken) || ts.isKeyword(contextToken.kind))) { var start_1 = ts.timestamp(); contextToken = ts.findPrecedingToken(contextToken.getFullStart(), sourceFile, /*startNode*/ undefined); // TODO: GH#18217 log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_1)); @@ -109720,7 +109761,7 @@ var ts; } } } - if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */)) { + if (ts.isMetaProperty(node) && (node.keywordToken === 99 /* NewKeyword */ || node.keywordToken === 96 /* ImportKeyword */) && contextToken === node.getChildAt(1)) { var completion = (node.keywordToken === 99 /* NewKeyword */) ? "target" : "meta"; symbols.push(typeChecker.createSymbol(4 /* Property */, ts.escapeLeadingUnderscores(completion))); return; @@ -111044,6 +111085,8 @@ var ts; if (!contextToken) return undefined; switch (contextToken.kind) { + case 62 /* EqualsToken */: // class c { public prop = | /* global completions */ } + return undefined; case 26 /* SemicolonToken */: // class c {getValue(): number; | } case 19 /* CloseBraceToken */: // class c { method() { } | } // class c { method() { } b| } @@ -111170,8 +111213,12 @@ var ts; case 103 /* SwitchKeyword */: return useParent(node.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); case 78 /* CaseKeyword */: - case 84 /* DefaultKeyword */: - return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + case 84 /* DefaultKeyword */: { + if (ts.isDefaultClause(node.parent) || ts.isCaseClause(node.parent)) { + return useParent(node.parent.parent.parent, ts.isSwitchStatement, getSwitchCaseDefaultOccurrences); + } + return undefined; + } case 77 /* BreakKeyword */: case 82 /* ContinueKeyword */: return useParent(node.parent, ts.isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences); @@ -112519,9 +112566,7 @@ var ts; return __assign(__assign({}, documentSpan), { isWriteAccess: false, isDefinition: false }); } var kind = entry.kind, node = entry.node; - return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === 84 /* DefaultKeyword */ - || !!ts.getDeclarationFromName(node) - || ts.isLiteralComputedPropertyDeclarationName(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); + return __assign(__assign({}, documentSpan), { isWriteAccess: isWriteAccessForReference(node), isDefinition: isDefinitionForReference(node), isInString: kind === 2 /* StringLiteral */ ? true : undefined }); } FindAllReferences.toReferenceEntry = toReferenceEntry; function entryToDocumentSpan(entry) { @@ -112629,6 +112674,12 @@ var ts; var decl = ts.getDeclarationFromName(node); return !!decl && declarationIsWriteAccess(decl) || node.kind === 84 /* DefaultKeyword */ || ts.isWriteAccess(node); } + function isDefinitionForReference(node) { + return node.kind === 84 /* DefaultKeyword */ + || !!ts.getDeclarationFromName(node) + || ts.isLiteralComputedPropertyDeclarationName(node) + || (node.kind === 129 /* ConstructorKeyword */ && ts.isConstructorDeclaration(node.parent)); + } /** * True if 'decl' provides a value, as in `function f() {}`; * false if 'decl' is just a location for a future write, as in 'let x;' @@ -122924,27 +122975,62 @@ var ts; this.insertNodeAtStartWorker(sourceFile, obj, newElement); }; ChangeTracker.prototype.insertNodeAtStartWorker = function (sourceFile, cls, newElement) { - var clsStart = cls.getStart(sourceFile); - var indentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) - + this.formatContext.options.indentSize; - this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, __assign({ indentation: indentation }, this.getInsertNodeAtStartPrefixSuffix(sourceFile, cls))); + var _a; + var indentation = (_a = this.guessIndentationFromExistingMembers(sourceFile, cls)) !== null && _a !== void 0 ? _a : this.computeIndentationForNewMember(sourceFile, cls); + this.insertNodeAt(sourceFile, getMembersOrProperties(cls).pos, newElement, this.getInsertNodeAtStartInsertOptions(sourceFile, cls, indentation)); }; - ChangeTracker.prototype.getInsertNodeAtStartPrefixSuffix = function (sourceFile, cls) { - var comma = ts.isObjectLiteralExpression(cls) ? "," : ""; - if (getMembersOrProperties(cls).length === 0) { - if (ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile })) { - // For `class C {\n}`, don't add the trailing "\n" - var _a = getClassOrObjectBraceEnds(cls, sourceFile), open = _a[0], close = _a[1]; - var shouldSuffix = open && close && ts.positionsAreOnSameLine(open, close, sourceFile); - return { prefix: this.newLineCharacter, suffix: comma + (shouldSuffix ? this.newLineCharacter : "") }; + /** + * Tries to guess the indentation from the existing members of a class/interface/object. All members must be on + * new lines and must share the same indentation. + */ + ChangeTracker.prototype.guessIndentationFromExistingMembers = function (sourceFile, cls) { + var indentation; + var lastRange = cls; + for (var _i = 0, _a = getMembersOrProperties(cls); _i < _a.length; _i++) { + var member = _a[_i]; + if (ts.rangeStartPositionsAreOnSameLine(lastRange, member, sourceFile)) { + // each indented member must be on a new line + return undefined; } - else { - return { prefix: "", suffix: comma + this.newLineCharacter }; + var memberStart = member.getStart(sourceFile); + var memberIndentation = ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(memberStart, sourceFile), memberStart, sourceFile, this.formatContext.options); + if (indentation === undefined) { + indentation = memberIndentation; } + else if (memberIndentation !== indentation) { + // indentation of multiple members is not consistent + return undefined; + } + lastRange = member; } - else { - return { prefix: this.newLineCharacter, suffix: comma }; - } + return indentation; + }; + ChangeTracker.prototype.computeIndentationForNewMember = function (sourceFile, cls) { + var _a; + var clsStart = cls.getStart(sourceFile); + return ts.formatting.SmartIndenter.findFirstNonWhitespaceColumn(ts.getLineStartPositionForPosition(clsStart, sourceFile), clsStart, sourceFile, this.formatContext.options) + + ((_a = this.formatContext.options.indentSize) !== null && _a !== void 0 ? _a : 4); + }; + ChangeTracker.prototype.getInsertNodeAtStartInsertOptions = function (sourceFile, cls, indentation) { + // Rules: + // - Always insert leading newline. + // - For object literals: + // - Add a trailing comma if there are existing members in the node, or the source file is not a JSON file + // (because trailing commas are generally illegal in a JSON file). + // - Add a leading comma if the source file is not a JSON file, there are existing insertions, + // and the node is empty (because we didn't add a trailing comma per the previous rule). + // - Only insert a trailing newline if body is single-line and there are no other insertions for the node. + // NOTE: This is handled in `finishClassesWithNodesInsertedAtStart`. + var members = getMembersOrProperties(cls); + var isEmpty = members.length === 0; + var isFirstInsertion = ts.addToSeen(this.classesWithNodesInsertedAtStart, ts.getNodeId(cls), { node: cls, sourceFile: sourceFile }); + var insertTrailingComma = ts.isObjectLiteralExpression(cls) && (!ts.isJsonSourceFile(sourceFile) || !isEmpty); + var insertLeadingComma = ts.isObjectLiteralExpression(cls) && ts.isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion; + return { + indentation: indentation, + prefix: (insertLeadingComma ? "," : "") + this.newLineCharacter, + suffix: insertTrailingComma ? "," : "" + }; }; ChangeTracker.prototype.insertNodeAfterComma = function (sourceFile, after, newNode) { var endPosition = this.insertNodeAfterWorker(sourceFile, this.nextCommaToken(sourceFile, after) || after, newNode); @@ -123146,9 +123232,16 @@ var ts; this.classesWithNodesInsertedAtStart.forEach(function (_a) { var node = _a.node, sourceFile = _a.sourceFile; var _b = getClassOrObjectBraceEnds(node, sourceFile), openBraceEnd = _b[0], closeBraceEnd = _b[1]; - // For `class C { }` remove the whitespace inside the braces. - if (openBraceEnd && closeBraceEnd && ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile) && openBraceEnd !== closeBraceEnd - 1) { - _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + if (openBraceEnd !== undefined && closeBraceEnd !== undefined) { + var isEmpty = getMembersOrProperties(node).length === 0; + var isSingleLine = ts.positionsAreOnSameLine(openBraceEnd, closeBraceEnd, sourceFile); + if (isEmpty && isSingleLine && openBraceEnd !== closeBraceEnd - 1) { + // For `class C { }` remove the whitespace inside the braces. + _this.deleteRange(sourceFile, ts.createRange(openBraceEnd, closeBraceEnd - 1)); + } + if (isSingleLine) { + _this.insertText(sourceFile, closeBraceEnd - 1, _this.newLineCharacter); + } } }); }; @@ -123724,10 +123817,10 @@ var ts; ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1)) : ts.getLocaleSpecificMessage(diag); } - function createCodeFixActionNoFixId(fixName, changes, description) { + function createCodeFixActionWithoutFixAll(fixName, changes, description) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } - codefix.createCodeFixActionNoFixId = createCodeFixActionNoFixId; + codefix.createCodeFixActionWithoutFixAll = createCodeFixActionWithoutFixAll; function createCodeFixAction(fixName, changes, description, fixId, fixAllDescription, command) { return createCodeFixActionWorker(fixName, diagnosticToString(description), changes, fixId, diagnosticToString(fixAllDescription), command); } @@ -123753,8 +123846,26 @@ var ts; return ts.arrayFrom(errorCodeToFixes.keys()); } codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function removeFixIdIfFixAllUnavailable(registration, diagnostics) { + var errorCodes = registration.errorCodes; + var maybeFixableDiagnostics = 0; + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diag = diagnostics_1[_i]; + if (ts.contains(errorCodes, diag.code)) + maybeFixableDiagnostics++; + if (maybeFixableDiagnostics > 1) + break; + } + var fixAllUnavailable = maybeFixableDiagnostics < 2; + return function (_a) { + var fixId = _a.fixId, fixAllDescription = _a.fixAllDescription, action = __rest(_a, ["fixId", "fixAllDescription"]); + return fixAllUnavailable ? action : __assign(__assign({}, action), { fixId: fixId, fixAllDescription: fixAllDescription }); + }; + } function getFixes(context) { - return ts.flatMap(errorCodeToFixes.get(String(context.errorCode)) || ts.emptyArray, function (f) { return f.getCodeActions(context); }); + var diagnostics = getDiagnostics(context); + var registrations = errorCodeToFixes.get(String(context.errorCode)); + return ts.flatMap(registrations, function (f) { return ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics)); }); } codefix.getFixes = getFixes; function getAllFixes(context) { @@ -123776,16 +123887,19 @@ var ts; return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } codefix.codeFixAll = codeFixAll; - function eachDiagnostic(_a, errorCodes, cb) { - var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; - for (var _i = 0, _b = program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); _i < _b.length; _i++) { - var diag = _b[_i]; + function eachDiagnostic(context, errorCodes, cb) { + for (var _i = 0, _a = getDiagnostics(context); _i < _a.length; _i++) { + var diag = _a[_i]; if (ts.contains(errorCodes, diag.code)) { cb(diag); } } } codefix.eachDiagnostic = eachDiagnostic; + function getDiagnostics(_a) { + var program = _a.program, sourceFile = _a.sourceFile, cancellationToken = _a.cancellationToken; + return program.getSemanticDiagnostics(sourceFile, cancellationToken).concat(ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken)); + } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -123842,6 +123956,28 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + var exportDeclaration = ts.createExportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createNamedExports([]), + /*moduleSpecifier*/ undefined, + /*isTypeOnly*/ false); + changes.insertNodeAtEndOfScope(sourceFile, sourceFile, exportDeclaration); + }); + return [codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)]; + }, + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -123912,7 +124048,9 @@ var ts; makeChange(t, errorCode, sourceFile, checker, expression, fixedDeclarations); } }); - return codefix.createCodeFixActionNoFixId("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 + // No fix-all because it will already be included once with the use site fix, + // and for simplicity the fix-all doesn‘t let the user choose between use-site and declaration-site fixes. + return codefix.createCodeFixActionWithoutFixAll("addMissingAwaitToInitializer", initializerChanges, awaitableInitializers.initializers.length === 1 ? [ts.Diagnostics.Add_await_to_initializer_for_0, awaitableInitializers.initializers[0].declarationSymbol.name] : ts.Diagnostics.Add_await_to_initializers); } @@ -124131,7 +124269,7 @@ var ts; if (forInitializer) return applyChange(changeTracker, forInitializer, sourceFile, fixedNodes); var parent = token.parent; - if (ts.isBinaryExpression(parent) && ts.isExpressionStatement(parent.parent)) { + if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isExpressionStatement(parent.parent)) { return applyChange(changeTracker, token, sourceFile, fixedNodes); } if (ts.isArrayLiteralExpression(parent)) { @@ -124193,7 +124331,9 @@ var ts; if (expression.operatorToken.kind === 27 /* CommaToken */) { return ts.every([expression.left, expression.right], function (expression) { return expressionCouldBeVariableDeclaration(expression, checker); }); } - return ts.isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); + return expression.operatorToken.kind === 62 /* EqualsToken */ + && ts.isIdentifier(expression.left) + && !checker.getSymbolAtLocation(expression.left); } })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); @@ -126184,7 +126324,7 @@ var ts; } }); // No support for fix-all since this applies to the whole file at once anyway. - return [codefix.createCodeFixActionNoFixId("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; + return [codefix.createCodeFixActionWithoutFixAll("convertToEs6Module", changes, ts.Diagnostics.Convert_to_ES6_module)]; }, }); function fixImportOfModuleExports(importingFile, exportingFile, changes, quotePreference) { @@ -126783,7 +126923,8 @@ var ts; (function (ts) { var codefix; (function (codefix) { - codefix.importFixId = "fixMissingImport"; + codefix.importFixName = "import"; + var importFixId = "fixMissingImport"; var errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, @@ -126804,7 +126945,7 @@ var ts; var quotePreference = ts.getQuotePreference(sourceFile, preferences); return fixes.map(function (fix) { return codeActionForFix(context, sourceFile, symbolName, fix, quotePreference); }); }, - fixIds: [codefix.importFixId], + fixIds: [importFixId], getAllCodeActions: function (context) { var sourceFile = context.sourceFile, preferences = context.preferences; // Namespace fixes don't conflict, so just build a list. @@ -127236,7 +127377,7 @@ var ts; var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { diag = codeActionForFixWorker(tracker, sourceFile, symbolName, fix, quotePreference); }); - return codefix.createCodeFixAction("import", changes, diag, codefix.importFixId, ts.Diagnostics.Add_all_missing_imports); + return codefix.createCodeFixAction(codefix.importFixName, changes, diag, importFixId, ts.Diagnostics.Add_all_missing_imports); } function codeActionForFixWorker(changes, sourceFile, symbolName, fix, quotePreference) { switch (fix.kind) { @@ -127534,17 +127675,17 @@ var ts; var info = getInfo(sourceFile, context.span.start, context); if (!info) return undefined; - var node = info.node, suggestion = info.suggestion; + var node = info.node, suggestedSymbol = info.suggestedSymbol; var target = context.host.getCompilationSettings().target; - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestion, target); }); - return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, suggestion], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return doChange(t, sourceFile, node, suggestedSymbol, target); }); + return [codefix.createCodeFixAction("spelling", changes, [ts.Diagnostics.Change_spelling_to_0, ts.symbolName(suggestedSymbol)], fixId, ts.Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var info = getInfo(diag.file, diag.start, context); var target = context.host.getCompilationSettings().target; if (info) - doChange(changes, context.sourceFile, info.node, info.suggestion, target); + doChange(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }); }, }); function getInfo(sourceFile, pos, context) { @@ -127553,34 +127694,42 @@ var ts; // ^^^^^^^ var node = ts.getTokenAtPosition(sourceFile, pos); var checker = context.program.getTypeChecker(); - var suggestion; + var suggestedSymbol; if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) { - ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (property access)"); + ts.Debug.assert(ts.isIdentifierOrPrivateIdentifier(node), "Expected an identifier for spelling (property access)"); var containingType = checker.getTypeAtLocation(node.parent.expression); if (node.parent.flags & 32 /* OptionalChain */) { containingType = checker.getNonNullableType(containingType); } - suggestion = checker.getSuggestionForNonexistentProperty(node, containingType); + var name = node; + suggestedSymbol = checker.getSuggestedSymbolForNonexistentProperty(name, containingType); } else if (ts.isImportSpecifier(node.parent) && node.parent.name === node) { ts.Debug.assert(node.kind === 75 /* Identifier */, "Expected an identifier for spelling (import)"); var importDeclaration = ts.findAncestor(node, ts.isImportDeclaration); var resolvedSourceFile = getResolvedSourceFileFromImportDeclaration(sourceFile, context, importDeclaration); if (resolvedSourceFile && resolvedSourceFile.symbol) { - suggestion = checker.getSuggestionForNonexistentExport(node, resolvedSourceFile.symbol); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentModule(node, resolvedSourceFile.symbol); } } else { var meaning = ts.getMeaningFromLocation(node); var name = ts.getTextOfNode(node); ts.Debug.assert(name !== undefined, "name should be defined"); - suggestion = checker.getSuggestionForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); + suggestedSymbol = checker.getSuggestedSymbolForNonexistentSymbol(node, name, convertSemanticMeaningToSymbolFlags(meaning)); } - return suggestion === undefined ? undefined : { node: node, suggestion: suggestion }; + return suggestedSymbol === undefined ? undefined : { node: node, suggestedSymbol: suggestedSymbol }; } - function doChange(changes, sourceFile, node, suggestion, target) { + function doChange(changes, sourceFile, node, suggestedSymbol, target) { + var suggestion = ts.symbolName(suggestedSymbol); if (!ts.isIdentifierText(suggestion, target) && ts.isPropertyAccessExpression(node.parent)) { - changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + var valDecl = suggestedSymbol.valueDeclaration; + if (ts.isNamedDeclaration(valDecl) && ts.isPrivateIdentifier(valDecl.name)) { + changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); + } + else { + changes.replaceNode(sourceFile, node.parent, ts.createElementAccess(node.parent.expression, ts.createLiteral(suggestion))); + } } else { changes.replaceNode(sourceFile, node, ts.createIdentifier(suggestion)); @@ -127844,7 +127993,7 @@ var ts; /*modifiers*/ undefined, [indexingParameter], typeNode); var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.insertNodeAtClassStart(declSourceFile, classDeclaration, indexSignature); }); // No fixId here because code-fix-all currently only works on adding individual named properties. - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Add_index_signature_for_property_0, tokenName]); } function getActionForMethodDeclaration(context, declSourceFile, classDeclaration, token, callExpression, makeStatic, inJs, preferences) { // Private methods are not implemented yet. @@ -128129,7 +128278,7 @@ var ts; return undefined; } var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return doChange(changeTracker, configFile); }); - return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; + return [codefix.createCodeFixActionWithoutFixAll(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; }, fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes) { @@ -128163,7 +128312,7 @@ var ts; return doChange(changeTracker, configFile); }); return [ - codefix.createCodeFixActionNoFixId(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) + codefix.createCodeFixActionWithoutFixAll(fixID, changes, ts.Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) ]; }, fixIds: [fixID], @@ -128184,6 +128333,49 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher.code], + getCodeActions: function (context) { + var compilerOptions = context.program.getCompilerOptions(); + var configFile = compilerOptions.configFile; + if (configFile === undefined) { + return undefined; + } + var codeFixes = []; + var moduleKind = ts.getEmitModuleKind(compilerOptions); + var moduleOutOfRange = moduleKind >= ts.ModuleKind.ES2015 && moduleKind < ts.ModuleKind.ESNext; + if (moduleOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { + codefix.setJsonCompilerOptionValue(changes, configFile, "module", ts.createStringLiteral("esnext")); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixModuleOption", changes, [ts.Diagnostics.Set_the_module_option_in_your_configuration_file_to_0, "esnext"])); + } + var target = ts.getEmitScriptTarget(compilerOptions); + var targetOutOfRange = target < 4 /* ES2017 */ || target > 99 /* ESNext */; + if (targetOutOfRange) { + var changes = ts.textChanges.ChangeTracker.with(context, function (tracker) { + var configObject = ts.getTsConfigObjectLiteralExpression(configFile); + if (!configObject) + return; + var options = [["target", ts.createStringLiteral("es2017")]]; + if (moduleKind === ts.ModuleKind.CommonJS) { + // Ensure we preserve the default module kind (commonjs), as targets >= ES2015 have a default module kind of es2015. + options.push(["module", ts.createStringLiteral("commonjs")]); + } + codefix.setJsonCompilerOptionValues(tracker, configFile, options); + }); + codeFixes.push(codefix.createCodeFixActionWithoutFixAll("fixTargetOption", changes, [ts.Diagnostics.Set_the_target_option_in_your_configuration_file_to_0, "es2017"])); + } + return codeFixes.length ? codeFixes : undefined; + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -128336,7 +128528,7 @@ var ts; }); if (deletion.length) { var name = ts.isComputedPropertyName(token.parent) ? token.parent : token; - result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_declaration_for_Colon_0, name.getText(sourceFile)])); + result.push(createDeleteFix(deletion, [ts.Diagnostics.Remove_unused_declaration_for_Colon_0, name.getText(sourceFile)])); } } var prefix = ts.textChanges.ChangeTracker.with(context, function (t) { return tryPrefixDeclaration(t, errorCode, sourceFile, token); }); @@ -128697,7 +128889,7 @@ var ts; (function (codefix) { var fixId = "fixAwaitInSyncFunction"; var errorCodes = [ - ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function.code, + ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator.code, ]; codefix.registerCodeFix({ @@ -128789,7 +128981,7 @@ var ts; } var fixes = [ // fixId unnecessary because adding `// @ts-nocheck` even once will ignore every error in the file. - codefix.createCodeFixActionNoFixId(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ + codefix.createCodeFixActionWithoutFixAll(fixName, [codefix.createFileTextChanges(sourceFile.fileName, [ ts.createTextChange(sourceFile.checkJsDirective ? ts.createTextSpanFromBounds(sourceFile.checkJsDirective.pos, sourceFile.checkJsDirective.end) : ts.createTextSpan(0, 0), "// @ts-nocheck" + ts.getNewLineOrDefaultFromHost(host, formatContext.options)), @@ -129056,29 +129248,37 @@ var ts; } return undefined; } - function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + function setJsonCompilerOptionValues(changeTracker, configFile, options) { var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (compilerOptionsProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ - createJsonPropertyAssignment(optionName, optionValue), - ]))); + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral(options.map(function (_a) { + var optionName = _a[0], optionValue = _a[1]; + return createJsonPropertyAssignment(optionName, optionValue); + }), /*multiLine*/ true))); return; } var compilerOptions = compilerOptionsProperty.initializer; if (!ts.isObjectLiteralExpression(compilerOptions)) { return; } - var optionProperty = findJsonProperty(compilerOptions, optionName); - if (optionProperty === undefined) { - changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); - } - else { - changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + for (var _i = 0, options_1 = options; _i < options_1.length; _i++) { + var _a = options_1[_i], optionName = _a[0], optionValue = _a[1]; + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } } } + codefix.setJsonCompilerOptionValues = setJsonCompilerOptionValues; + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]); + } codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; function createJsonPropertyAssignment(name, initializer) { return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); @@ -129113,7 +129313,7 @@ var ts; } function createAction(context, sourceFile, node, replacement) { var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile, node, replacement); }); - return codefix.createCodeFixActionNoFixId(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); + return codefix.createCodeFixActionWithoutFixAll(fixName, changes, [ts.Diagnostics.Replace_import_with_0, changes[0].textChanges[0].newText]); } codefix.registerCodeFix({ errorCodes: [ @@ -129171,7 +129371,7 @@ var ts; if (ts.isExpression(expr) && !(ts.isNamedDeclaration(expr.parent) && expr.parent.name === expr)) { var sourceFile_1 = context.sourceFile; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return t.replaceNode(sourceFile_1, expr, ts.createPropertyAccess(expr, "default"), {}); }); - fixes.push(codefix.createCodeFixActionNoFixId(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); + fixes.push(codefix.createCodeFixActionWithoutFixAll(fixName, changes, ts.Diagnostics.Use_synthetic_default_member)); } return fixes; } diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 068bc5dba19..c4ee140de74 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -1264,6 +1264,11 @@ var ts; return result; } ts.clone = clone; + /** + * Creates a new object by adding the own properties of `second`, then the own properties of `first`. + * + * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen. + */ function extend(first, second) { var result = {}; for (var id in second) { @@ -5584,10 +5589,13 @@ var ts; } } function readFileWorker(fileName, _encoding) { - if (!fileExists(fileName)) { + var buffer; + try { + buffer = _fs.readFileSync(fileName); + } + catch (e) { return undefined; } - var buffer = _fs.readFileSync(fileName); var len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, @@ -5637,23 +5645,30 @@ var ts; function getAccessibleFileSystemEntries(path) { ts.perfLogger.logEvent("ReadDir: " + (path || ".")); try { - var entries = _fs.readdirSync(path || ".").sort(); + var entries = _fs.readdirSync(path || ".", { withFileTypes: true }); var files = []; var directories = []; for (var _i = 0, entries_2 = entries; _i < entries_2.length; _i++) { - var entry = entries_2[_i]; + var dirent = entries_2[_i]; + // withFileTypes is not supported before Node 10.10. + var entry = typeof dirent === "string" ? dirent : dirent.name; // This is necessary because on some file system node fails to exclude // "." and "..". See https://github.com/nodejs/node/issues/4002 if (entry === "." || entry === "..") { continue; } - var name = ts.combinePaths(path, entry); var stat = void 0; - try { - stat = _fs.statSync(name); + if (typeof dirent === "string" || dirent.isSymbolicLink()) { + var name = ts.combinePaths(path, entry); + try { + stat = _fs.statSync(name); + } + catch (e) { + continue; + } } - catch (e) { - continue; + else { + stat = dirent; } if (stat.isFile()) { files.push(entry); @@ -5662,6 +5677,8 @@ var ts; directories.push(entry); } } + files.sort(); + directories.sort(); return { files: files, directories: directories }; } catch (e) { @@ -5691,8 +5708,7 @@ var ts; return fileSystemEntryExists(path, 1 /* Directory */); } function getDirectories(path) { - ts.perfLogger.logEvent("ReadDir: " + path); - return ts.filter(_fs.readdirSync(path), function (dir) { return fileSystemEntryExists(ts.combinePaths(path, dir), 1 /* Directory */); }); + return getAccessibleFileSystemEntries(path).directories.slice(); } function realpath(path) { try { @@ -6686,7 +6702,7 @@ var ts; Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."), Already_included_file_name_0_differs_from_file_name_1_only_in_casing: diag(1261, ts.DiagnosticCategory.Error, "Already_included_file_name_0_differs_from_file_name_1_only_in_casing_1261", "Already included file name '{0}' differs from file name '{1}' only in casing."), with_statements_are_not_allowed_in_an_async_function_block: diag(1300, ts.DiagnosticCategory.Error, "with_statements_are_not_allowed_in_an_async_function_block_1300", "'with' statements are not allowed in an async function block."), - await_expression_is_only_allowed_within_an_async_function: diag(1308, ts.DiagnosticCategory.Error, "await_expression_is_only_allowed_within_an_async_function_1308", "'await' expression is only allowed within an async function."), + await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules: diag(1308, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules_1308", "'await' expressions are only allowed within async functions and at the top levels of modules."), can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: diag(1312, ts.DiagnosticCategory.Error, "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", "'=' can only be used in an object literal property inside a destructuring assignment."), The_body_of_an_if_statement_cannot_be_the_empty_statement: diag(1313, ts.DiagnosticCategory.Error, "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", "The body of an 'if' statement cannot be the empty statement."), Global_module_exports_may_only_appear_in_module_files: diag(1314, ts.DiagnosticCategory.Error, "Global_module_exports_may_only_appear_in_module_files_1314", "Global module exports may only appear in module files."), @@ -6734,14 +6750,13 @@ var ts; An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), - Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"), Type_only_0_must_reference_a_type_but_1_is_a_value: diag(1361, ts.DiagnosticCategory.Error, "Type_only_0_must_reference_a_type_but_1_is_a_value_1361", "Type-only {0} must reference a type, but '{1}' is a value."), Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported: diag(1362, ts.DiagnosticCategory.Error, "Enum_0_cannot_be_used_as_a_value_because_only_its_type_has_been_imported_1362", "Enum '{0}' cannot be used as a value because only its type has been imported."), A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both: diag(1363, ts.DiagnosticCategory.Error, "A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both_1363", "A type-only import can specify a default import or named bindings, but not both."), Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"), Convert_all_re_exported_types_to_type_only_exports: diag(1365, ts.DiagnosticCategory.Message, "Convert_all_re_exported_types_to_type_only_exports_1365", "Convert all re-exported types to type-only exports"), Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"), - Split_all_invalid_type_only_imports: diag(1377, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1377", "Split all invalid type-only imports"), + Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"), Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"), Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"), Only_ECMAScript_imports_may_use_import_type: diag(1370, ts.DiagnosticCategory.Error, "Only_ECMAScript_imports_may_use_import_type_1370", "Only ECMAScript imports may use 'import type'."), @@ -6749,7 +6764,8 @@ var ts; This_import_may_be_converted_to_a_type_only_import: diag(1372, ts.DiagnosticCategory.Suggestion, "This_import_may_be_converted_to_a_type_only_import_1372", "This import may be converted to a type-only import."), Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"), Convert_all_imports_not_used_as_a_value_to_type_only_imports: diag(1374, ts.DiagnosticCategory.Message, "Convert_all_imports_not_used_as_a_value_to_type_only_imports_1374", "Convert all imports not used as a value to type-only imports"), - await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher: diag(1375, ts.DiagnosticCategory.Error, "await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnex_1375", "'await' outside of an async function is only allowed at the top level of a module when '--module' is 'esnext' or 'system' and '--target' is 'es2017' or higher."), + await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module: diag(1375, ts.DiagnosticCategory.Error, "await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_fi_1375", "'await' expressions are only allowed at the top level of a file when that file is a module, but this file has no imports or exports. Consider adding an empty 'export {}' to make this file a module."), + Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1376, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1376", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -7695,7 +7711,7 @@ var ts; Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"), Make_super_call_the_first_statement_in_the_constructor: diag(90002, ts.DiagnosticCategory.Message, "Make_super_call_the_first_statement_in_the_constructor_90002", "Make 'super()' call the first statement in the constructor"), Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"), - Remove_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_declaration_for_Colon_0_90004", "Remove declaration for: '{0}'"), + Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"), Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"), Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"), Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"), @@ -7818,10 +7834,12 @@ var ts; Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"), Prefix_all_incorrect_property_declarations_with_declare: diag(95095, ts.DiagnosticCategory.Message, "Prefix_all_incorrect_property_declarations_with_declare_95095", "Prefix all incorrect property declarations with 'declare'"), Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"), + Add_export_to_make_this_file_into_a_module: diag(95097, ts.DiagnosticCategory.Message, "Add_export_to_make_this_file_into_a_module_95097", "Add 'export {}' to make this file into a module"), + Set_the_target_option_in_your_configuration_file_to_0: diag(95098, ts.DiagnosticCategory.Message, "Set_the_target_option_in_your_configuration_file_to_0_95098", "Set the 'target' option in your configuration file to '{0}'"), + Set_the_module_option_in_your_configuration_file_to_0: diag(95099, ts.DiagnosticCategory.Message, "Set_the_module_option_in_your_configuration_file_to_0_95099", "Set the 'module' option in your configuration file to '{0}'"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, ts.DiagnosticCategory.Error, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, ts.DiagnosticCategory.Error, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, ts.DiagnosticCategory.Error, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), - can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Private_identifiers_cannot_be_used_as_parameters: diag(18009, ts.DiagnosticCategory.Error, "Private_identifiers_cannot_be_used_as_parameters_18009", "Private identifiers cannot be used as parameters"), An_accessibility_modifier_cannot_be_used_with_a_private_identifier: diag(18010, ts.DiagnosticCategory.Error, "An_accessibility_modifier_cannot_be_used_with_a_private_identifier_18010", "An accessibility modifier cannot be used with a private identifier."), The_operand_of_a_delete_operator_cannot_be_a_private_identifier: diag(18011, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_cannot_be_a_private_identifier_18011", "The operand of a 'delete' operator cannot be a private identifier."), @@ -7836,6 +7854,7 @@ var ts; A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."), An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."), An_enum_member_cannot_be_named_with_a_private_identifier: diag(18024, ts.DiagnosticCategory.Error, "An_enum_member_cannot_be_named_with_a_private_identifier_18024", "An enum member cannot be named with a private identifier."), + can_only_be_used_at_the_start_of_a_file: diag(18026, ts.DiagnosticCategory.Error, "can_only_be_used_at_the_start_of_a_file_18026", "'#!' can only be used at the start of a file."), Compiler_reserves_name_0_when_emitting_private_identifier_downlevel: diag(18027, ts.DiagnosticCategory.Error, "Compiler_reserves_name_0_when_emitting_private_identifier_downlevel_18027", "Compiler reserves name '{0}' when emitting private identifier downlevel."), Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher: diag(18028, ts.DiagnosticCategory.Error, "Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher_18028", "Private identifiers are only available when targeting ECMAScript 2015 and higher."), Private_identifiers_are_not_allowed_in_variable_declarations: diag(18029, ts.DiagnosticCategory.Error, "Private_identifiers_are_not_allowed_in_variable_declarations_18029", "Private identifiers are not allowed in variable declarations."), @@ -26027,6 +26046,7 @@ var ts; error: 2 /* Error */ }), affectsEmit: true, + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types }, @@ -26284,12 +26304,15 @@ var ts; { name: "experimentalDecorators", type: "boolean", + affectsSemanticDiagnostics: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators }, { name: "emitDecoratorMetadata", type: "boolean", + affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Experimental_Options, description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators }, @@ -26303,6 +26326,7 @@ var ts; { name: "resolveJsonModule", type: "boolean", + affectsModuleResolution: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Include_modules_imported_with_json_extension }, @@ -26507,6 +26531,7 @@ var ts; name: "useDefineForClassFields", type: "boolean", affectsSemanticDiagnostics: true, + affectsEmit: true, category: ts.Diagnostics.Advanced_Options, description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set, }, @@ -30383,7 +30408,7 @@ var ts; case 104 /* ThisKeyword */: case 194 /* PropertyAccessExpression */: case 195 /* ElementAccessExpression */: - return isNarrowableReference(expr); + return containsNarrowableReference(expr); case 196 /* CallExpression */: return hasNarrowableArgument(expr); case 200 /* ParenthesizedExpression */: @@ -30400,20 +30425,22 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 104 /* ThisKeyword */ || expr.kind === 102 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || - ts.isOptionalChain(expr); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression); + } + function containsNarrowableReference(expr) { + return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression); } function hasNarrowableArgument(expr) { if (expr.arguments) { for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) { var argument = _a[_i]; - if (isNarrowableReference(argument)) { + if (containsNarrowableReference(argument)) { return true; } } } if (expr.expression.kind === 194 /* PropertyAccessExpression */ && - isNarrowableReference(expr.expression.expression)) { + containsNarrowableReference(expr.expression.expression)) { return true; } return false; @@ -30427,7 +30454,7 @@ var ts; function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { case 62 /* EqualsToken */: - return isNarrowableReference(expr.left); + return containsNarrowableReference(expr.left); case 34 /* EqualsEqualsToken */: case 35 /* ExclamationEqualsToken */: case 36 /* EqualsEqualsEqualsToken */: @@ -30455,7 +30482,7 @@ var ts; return isNarrowableOperand(expr.right); } } - return isNarrowableReference(expr); + return containsNarrowableReference(expr); } function createBranchLabel() { return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); @@ -33867,6 +33894,7 @@ var ts; var currentNode; var emptySymbols = ts.createSymbolTable(); var identityMapper = ts.identity; + var arrayVariances = [1 /* Covariant */]; var compilerOptions = host.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var moduleKind = ts.getEmitModuleKind(compilerOptions); @@ -34115,9 +34143,12 @@ var ts; isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, - getSuggestionForNonexistentProperty: function (node, type) { return getSuggestionForNonexistentProperty(node, type); }, + getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty, + getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty, + getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); }, - getSuggestionForNonexistentExport: function (node, target) { return getSuggestionForNonexistentExport(node, target); }, + getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule, + getSuggestionForNonexistentExport: getSuggestionForNonexistentExport, getBaseConstraintOfType: getBaseConstraintOfType, getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; }, resolveName: function (name, location, meaning, excludeGlobals) { @@ -35709,9 +35740,11 @@ var ts; // if symbolFromVariable is export - get its final target symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias); var symbolFromModule = getExportOfModule(targetSymbol, name.escapedText, dontResolveAlias); - // If the export member we're looking for is default, and there is no real default but allowSyntheticDefaultImports is on, return the entire module as the default - if (!symbolFromModule && allowSyntheticDefaultImports && name.escapedText === "default" /* Default */) { - symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) { + symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); + } } var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : @@ -45352,8 +45385,9 @@ var ts; } /** We approximate own properties as non-methods plus methods that are inside the object literal */ function isSpreadableProperty(prop) { - return !(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || - !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }); + return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) && + (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) || + !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); })); } function getSpreadSymbol(prop, readonly) { var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */); @@ -47679,6 +47713,9 @@ var ts; source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { var variances = getAliasVariances(source.aliasSymbol); + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -47873,6 +47910,12 @@ var ts; // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. var variances = getVariances(source.target); + // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This + // effectively means we measure variance only from type parameter occurrences that aren't nested in + // recursive instantiations of the generic type. + if (variances === ts.emptyArray) { + return 1 /* Maybe */; + } var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState); if (varianceResult !== undefined) { return varianceResult; @@ -48658,8 +48701,7 @@ var ts; // a digest of the type comparisons that occur for each type argument when instantiations of the // generic type are structurally compared. We infer the variance information by comparing // instantiations of the generic type for type arguments with known relations. The function - // returns the emptyArray singleton if we're not in strictFunctionTypes mode or if the function - // has been invoked recursively for the given generic type. + // returns the emptyArray singleton when invoked recursively for the given generic type. function getVariancesWorker(typeParameters, cache, createMarkerType) { if (typeParameters === void 0) { typeParameters = ts.emptyArray; } var variances = cache.variances; @@ -48706,9 +48748,9 @@ var ts; return variances; } function getVariances(type) { - // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) + // Arrays and tuples are known to be covariant, no need to spend time computing this. if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) { - return ts.emptyArray; + return arrayVariances; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); } @@ -52414,24 +52456,7 @@ var ts; } } else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) { - var diag = error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); - // See GH:32846 - if the user is using a variable whose type is () => T1 | ... | undefined - // they may have meant to specify the type as (() => T1 | ...) | undefined - // This is assumed if: the type is a FunctionType, the return type is a Union, the last constituent of - // the union is `undefined` - if (type.symbol && type.symbol.declarations.length === 1 && ts.isFunctionTypeNode(type.symbol.declarations[0])) { - var funcTypeNode = type.symbol.declarations[0]; - var returnType = getReturnTypeFromAnnotation(funcTypeNode); - if (returnType && returnType.flags & 1048576 /* Union */) { - var unionTypes_3 = funcTypeNode.type.types; - if (unionTypes_3 && unionTypes_3[unionTypes_3.length - 1].kind === 146 /* UndefinedKeyword */) { - var parenedFuncType = ts.getMutableClone(funcTypeNode); - // Highlight to the end of the second to last constituent of the union - parenedFuncType.end = unionTypes_3[unionTypes_3.length - 2].end; - ts.addRelatedInfo(diag, ts.createDiagnosticForNode(parenedFuncType, ts.Diagnostics.Did_you_mean_to_parenthesize_this_function_type)); - } - } - } + error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; } @@ -58046,12 +58071,17 @@ var ts; if (!(node.flags & 32768 /* AwaitContext */)) { if (isTopLevelAwait(node)) { var sourceFile = ts.getSourceFileOfNode(node); - if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || - languageVersion < 4 /* ES2017 */ || - !ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { - if (!hasParseDiagnostics(sourceFile)) { - var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_outside_of_an_async_function_is_only_allowed_at_the_top_level_of_a_module_when_module_is_esnext_or_system_and_target_is_es2017_or_higher); + if (!hasParseDiagnostics(sourceFile)) { + var span = void 0; + if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { + if (!span) + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module); + diagnostics.add(diagnostic); + } + if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) { + span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher); diagnostics.add(diagnostic); } } @@ -58061,7 +58091,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos); - var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expression_is_only_allowed_within_an_async_function); + var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules); var func = ts.getContainingFunction(node); if (func && func.kind !== 162 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) { var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async); @@ -96825,12 +96855,12 @@ var ts; if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; } - // If number of files in the program do not match, it is not up-to-date - if (program.getRootFileNames().length !== rootFileNames.length) { + // If root file names don't match + if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) { return false; } var seenResolvedRefs; - // If project references dont match + // If project references don't match if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) { return false; } diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index 6496c4afa54..44e599285ae 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -454,7 +454,7 @@ "Generic_type_0_requires_1_type_argument_s_2314": "泛型類型 '{0}' 需要 {1} 個型別引數。", "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "泛型型別 '{0}' 需要介於 {1} 和 {2} 之間的型別引數。", "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "泛型類型具現化的深度過深,而且可能是無限深。", - "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "getter 和 setter 存取子的可視性不符。", + "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "getter 和 setter 存取子的可見度不符。", "Global_module_exports_may_only_appear_at_top_level_1316": "全域模組匯出只能顯示在最上層。", "Global_module_exports_may_only_appear_in_declaration_files_1315": "全域模組匯出只能顯示在宣告檔案中。", "Global_module_exports_may_only_appear_in_module_files_1314": "全域模組匯出只能顯示在模組檔案中。",